标签: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
原文地址:http://taoyouth.blog.51cto.com/2793776/1745742