php curl 百度搜索关键词

本文介绍了一种使用PHP通过curl模拟浏览器请求百度搜索引擎的方法,实现了对特定关键词搜索结果的相关搜索词的抓取。该过程涉及到了关键词的URL编码、HTTP头部信息的模拟及结果的正则表达式匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

$key_word = urlencode('王者荣耀');//需要对关键词进行url解析,否者部分带字符的标题会返回空
$url = 'https://www.baidu.com/s?ie=UTF-8&wd='.$key_word;
 
$res = curl_request($url);
 
$reach_word = substr($res,strpos($res, '<div id="rs"><div class="tt">相关搜索'),strpos($res, '<div id="page" >')-strpos($res, '<div id="rs"><div class="tt">相关搜索') );//截取需要的内容
 
preg_match('/<a.*?">(.*?)<\/a>/', $reach_word,$match);//正则匹配第一个搜索词
$reach_word = @$match[1];
 
 
 
//curl获取百度内容
function curl_request($url, $data=null, $method='get', $https=true){
    $ch = curl_init();//初始化
    curl_setopt($ch, CURLOPT_URL, $url);//访问的URL
    curl_setopt($ch, CURLOPT_HEADER, false);//设置不需要头信息
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//只获取页面内容,但不输出
    if($https){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//https请求 不验证证书 
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//https请求 不验证HOST
    }
    curl_setopt($ch,CURLOPT_ENCODING,'gzip');//百度返回的内容进行了gzip压缩,需要用这个设置解析
    //curl模拟头部信息
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		    'Accept: */*',
			'Accept-Encoding: gzip, deflate, br',
			'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8',
			'Connection: keep-alive',
			'Host: www.baidu.com',
			'is_referer: https://www.baidu.com/',
			'is_xhr: 1',
			'Referer: https://www.baidu.com/',
			'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
			'X-Requested-With: XMLHttpRequest',
		));
    if($method == 'post'){
            curl_setopt($ch, CURLOPT_POST, true);//请求方式为post请求
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//请求数据
    }
    $result = curl_exec($ch);//执行请求
    curl_close($ch);//关闭curl,释放资源
    $result = mb_convert_encoding($result, 'utf-8', 'GBK,UTF-8,ASCII,gb2312');//百度默认编码是gb2312 这个设置转化为utf8编码
    return $result;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值