1

几个星期以来,我一直在各种页面上运行我的简单 dom 脚本,但从未遇到任何问题。现在,今天,当我尝试:

$html = file_get_html('http://www.sony.co.za/product/dsc-wx10');

我得到:

( ! ) Warning: file_get_contents(http://www.sony.co.za/product/dsc-wx10) 
[function.file-get-contents]: failed to open stream: HTTP request failed!
 in C:\XXXXXXX\simplephpdom\simple_html_dom.php on line 70

当以下工作时,可能导致我无法成功输入上面的代码:

 $html = file_get_html('http://www.google.com');
 $html = file_get_html('http://www.whatever.com');

我可以通过我的浏览器访问索尼页面。据我了解,上面的代码连接到端口 80,就像我一样。所以我很难相信我被封锁了。而且,我从第一天就被阻止了。

有什么想法可能导致这种情况吗?

4

3 回答 3

3

该站点似乎永远延迟了包含 PHP 用户代理的请求。听起来像是一个非常非常糟糕的阻止爬虫的尝试。

解决方案很简单:使用 curl 发送请求并指定“普通”用户代理。


更新:显然它还阻止空/丢失的用户代理:

> nc www.sony.co.za 80
nc: using stream socket
GET / HTTP/1.0
Host: www.sony.co.za
User-Agent: Mozilla Firefox

HTTP/1.0 301 Moved Permanently
...

对比

> nc www.sony.co.za 80
nc: using stream socket
GET / HTTP/1.0
Host: www.sony.co.za
[no response]
于 2012-04-17T08:05:15.827 回答
1

我可以看到你正在使用simple_html_domhttp://simplehtmldom.sourceforge.net/)......而不是使用file_get_html你可以str_get_html使用curl

include 'simple_html_dom.php';
$url="http://www.sony.co.za/product/dsc-wx10";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9");
$exec = curl_exec ($ch);
$html = str_get_html($exec);
var_dump($html);
于 2012-04-17T08:37:58.147 回答
1

您需要设置用户代理(标题),然后它可以工作:

$options = array(
    'http' => array(
            'user_agent' => 'Mozilla Firefox'
    )
);
$context = stream_context_create($options);
$url = 'http://www.sony.co.za/product/dsc-wx10';
$str = file_get_contents($url, 0, $context);
$html = str_get_html($str);

简单的 HTML DOM 需要您为它完成工作(从远程服务器加载字符串),我通常会说您应该DOMDocument代替那个“简单”的 HTML DOM 库,因为它更好地集成和更强大(并且实际上可以工作):

$options = array(
    'http' => array(
            'user_agent' => 'Mozilla Firefox'
    )
);
$context = stream_context_create($options);
libxml_set_streams_context($context);
$url = 'http://www.sony.co.za/product/dsc-wx10';
$doc = DOMDocument::loadHTMLFile($url);
于 2012-04-17T09:19:15.850 回答