【发布时间】:2015-12-23 20:33:46
【问题描述】:
我想获取 Youtube URL (https) 的源代码,类似于我们在浏览器中看到的“查看页面源代码”选项。
以下是我的 php 代码 - (index.php)
<?php
function gethtml($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$ip=rand(0,255).'.'.rand(0,255).'.'.rand(0,255).'.'.rand(0,255);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: $ip", "HTTP_X_FORWARDED_FOR: $ip"));
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/".rand(3,5).".".rand(0,3)." (Windows NT ".rand(3,5).".".rand(0,2)."; rv:2.0.1) Gecko/20100101 Firefox/".rand(3,5).".0.1");
$html = curl_exec($ch);
curl_close($ch);
return $html;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$url = $_REQUEST["url"];
$html = gethtml($url);
echo htmlspecialchars($html);
}
?>
<html>
<head></head>
<body>
<form name="test" method="POST" action="./index.php"/>
URL : <input type="text" name="url"/>
<br>
<input type="submit" value="See HTML" name="submit"/>
<br>
</form>
</body>
</html>
它适用于其他 URL,但不适用于任何 youtube URL。为什么?
【问题讨论】:
-
CURLOPT_HTTPHEADER 技巧毫无意义,不会“欺骗”他们相信您的请求来自那里......
-
但是为什么呢?它会向他们发送一个随机 IP 作为消息头,不是吗?
-
$_SERVER['REMOTE_ADDR'] 给出了将请求发送到 Web 服务器的 IP 地址。这通常是访问者的地址。 See this
-
多看看@Mercury,试试anatomy of HTTP ..。您缺少的是 TCP 为 HTTP 提供连接,我认为服务器将忽略您在标头中放置的任何内容并使用 TCP 连接中的详细信息。
-
所以您是说 Web 服务器没有考虑在请求网页的数据包中传递的标头,它需要 TCP 连接状态?
标签: php curl web-scraping