【发布时间】:2011-12-13 20:17:06
【问题描述】:
我正在尝试使用 PHP 抓取 Google 搜索结果。
我尝试使用 @file_get_contents(http://www.google.com/search?hl=en&q=test) 但它不起作用。它仅适用于http://www.google.com。
我尝试改用 curl。这是我的功能:
function my_fetch($url,$user_agent='Mozilla/4.0 (compatible; MSIE
5.01; Windows NT 5.0)') {
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_REFERER, 'http://www.google.com/');
$result = curl_exec ($ch);
curl_close ($ch);
return $result; }
$googleContent = my_fetch("http://www.google.com/search?hl=en&q=test");
echo $googleContent;
结果是
302 Moved
The document has moved here.
这里有一个链接:http://www.google.com/sorry/?continue=http://www.google.com/search%3Fhl%3Den%26q%3Dtest
有没有不用学习API就可以使用PHP爬取搜索结果的方法?
【问题讨论】:
-
我认为学习 API 更可行。
-
抓取 Google 搜索结果违反了他们的TOS。请改用Custom Search API。
-
code.google.com/apis/customsearch/v1/reference.html 涵盖了当前的搜索 API,需要一个 API 密钥。由于搜索公司最终想要赚钱,他们不会让搜索结果页面易于抓取。
-
现在它显示了正确的结果,试试吧....
-
使用 Search API 无法获得准确的排名,并且数据量受到严格限制,即使是相当昂贵的商业排序对于大量数据也无用。关于 TOS,您访问 Google 不接受 TOS,如果您之前接受过(例如使用 Google 帐户时),您可以书面声明拒绝它,而不是它起作用,如果您不造成麻烦,Google 将不要因为刮它们而追捕你。 scraping.compunect.com 有一个开源 PHP 项目,它使 Google 可靠。我想我的答案来得太晚了:)
标签: php web-scraping