当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP使用curl制作简易百度搜索

PHP使用curl制作简易百度搜索

2017年12月12日  | 移动技术网IT编程  | 我要评论

这几天研究了一下php中的curl类库,做了一个简单的百度搜索,先上代码

<div style="width:200px;height:100px;">
 <div>百度搜索</div>
 <form action="" method="get">
  <input type="text" name="key">
  <input type="submit" value="搜索">
 </form>
</div>
<?php
$k = '';
$k = !empty($_get['key'])?$_get['key']:'';
session_start();
$_session['key'] = $k;

$curl = curl_init(); 
// 设置你需要抓取的url 

for($i = 0;$i<2;$i++){
curl_setopt($curl, curlopt_url, "http://www.baidu.com/s?wd={$_session['key']}&pn={$i}"); 
// 设置header 
curl_setopt($curl, curlopt_header, 1); 
// 设置curl 参数,要求结果保存到字符串中还是输出到屏幕上。 
curl_setopt($curl, curlopt_returntransfer, 1); 
// 运行curl,请求网页 
$data = curl_exec($curl); 

$pre = '/<h3 class="t"><a.*?href = "(.*?)".*?target="_blank".*?>(.*?)<\/a><\/h3>/s';
preg_match_all($pre,$data,$match);

foreach ($match[1] as $k => $v) {
?> 
<div style="font-size:20px;color:red;">
 <a href="<?php echo $v;?>" target="_blank"><?php echo strip_tags($match[2][$k]);?></a>
</div>
<?php
}
}

curl_close($curl);


?>

经过分析百度的搜索时的url发现有一个规律

https://www.baidu.com/s?wd=搜索的关键字

但是我发现使用https协议后不能够获得百度上的数据于是改为http://www.baidu.com?wd=搜索的关键字就可以啦!!

效果图如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网