使用php的curl依據關鍵詞爬取百度搜尋結果頁

來源:互聯網
上載者:User
使用php的curl根據關鍵詞爬取百度搜尋結果頁
我想實現的是每次根據給出的關鍵詞搜尋百度結果頁,比如百度搜尋結果是這樣的,百度推廣內容加本文:

而我使用curl爬取結果是這樣的:

也就是說每次爬取結果都是無法爬取到百度推廣的內容。請問哪位大師能指導一下,鄙人剛入門,望各位不吝指導。先謝過了。
其中php抓取代碼如下:

$url = "http://www.baidu.com/s?wd=生命動力";
// 構造包頭,類比瀏覽器請求
$header = array (
"Host:www.baidu.com",
"Content-Type:application/x-www-form-urlencoded",//post請求
"Connection: keep-alive",
'Referer:http://www.baidu.com',
'User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BIDUBrowser 2.6)'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
// 執行
$content = curl_exec ( $ch );
if ($content == FALSE) {
echo "error:" . curl_error ( $ch );
}
// 關閉
curl_close ( $ch );

//輸出結果
echo $content;
?>

------解決思路----------------------
你的user-agent沒有類比好,所以不行。
其實根本不需要用post,直接用get就可以了。
修改如下:

$url = "http://www.baidu.com/s?wd=生命動力";

$header = array (
'User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
// 執行
$content = curl_exec ( $ch );
if ($content == FALSE) {
echo "error:" . curl_error ( $ch );
}
// 關閉
curl_close ( $ch );

//輸出結果
echo $content;


  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.