php数据抓取
我们得到输入关键字后在百度上搜索出来的第一条记录。例如:
代码如下:
<?php
if($_POST['donow']){
if($_POST['keys']){
$keys = trim($_POST['keys']);
$keystr = backstr($keys);
$urls = “https://www.baidu.com/s?wd=$keystr“;
$content = file_get_contents($urls);
$c1 = “/<table (border=”0″)?(s)?cellpadding=”0″ cellspacing=”0″ class=”result” id=”(.*)”>(.*)</table><br>/Uis”;
preg_match_all($c1,$content,$arr1);
echo $arr1[0][0];
}
}
//处理字符串函数,将字符串处理成百度搜索格式的
function backstr($keys){
$keysa = explode(” “,$keys);
$output = ”;
$ara = array();
for($k=0;$k<sizeof($keysa);$k++){
if(!preg_match(’/(w).*/’,$keysa[$k],$arrk)){
$output = ”;
$tab_text = str_split($keysa[$k]);
foreach ($tab_text as $id=>$char){
$hex = dechex(ord($char));
$output.= ‘%’ . $hex;
}
}else{
$output = $keysa[$k];
}
array_push($ara,$output);
}
$output = implode(”+”,$ara);
return $output;
}
?>
<form action=”" method=”POST”>
<table width=”30%” border=”1″ align=”center”>
<tr><td>关键字:<input type=”text” name=”keys” id=”keys” value=”<?php echo $keys;?>” size=”30″></td></tr>
<tr><td><input type=”submit” name=”donow” value=”立即搜索”></tr>
</table>
</form>
得到结果:
注:本php函数需要您的配置环境支持的前提才能抓取到数据;
抓取不同的页面需要修改相应的正则表达式。
最后更新:2017-01-04 22:34:39