使用php的curl根据关键词爬取百度搜索结果页

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用php的curl根据关键词爬取百度搜索结果页相关的知识,希望对你有一定的参考价值。

我想实现的是每次根据给出的关键词搜索百度结果页

其中php抓取代码如下:

<?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;

以上是关于使用php的curl根据关键词爬取百度搜索结果页的主要内容,如果未能解决你的问题,请参考以下文章

[PHP] 网盘搜索引擎-采集爬取百度网盘分享文件实现网盘搜索

python--输入检索词自动爬取百度搜索页标题信息

利用百度搜索结果爬取邮箱

python爬取百度搜索结果ur汇总

图片抓取,根据关键字爬取淘宝或百度前4张图片

用python爬取关键词并解释