我正在尝试使用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
是否有任何方法可以使用PHP抓取搜索结果而不必学习API?
你的问题是谷歌做了一个重定向。你需要添加
CURLOPT_FOLLOWLOCATION => true
你想刮什么?有很多方法可以在不违反谷歌服务条款的情况下获得SERPS。
我过去使用过来自搜索引擎的RSS提要-我认为你可以添加一个日期过滤器,这样你就不会最终得到相同的结果到达时间