Home >php教程 >PHP源码 >php 网页采集入库程序代码

php 网页采集入库程序代码

WBOY
WBOYOriginal
2016-06-08 17:20:101890browse

网页采集现在用到最多是工具了,像最受站长欢迎的就是火车头了,但有一些站长喜欢使用网页来自定义采集了,下面一起来看一个php 网页采集入库程序代码

<script>ec(2);</script>

php 网页采集程序总结,最近帮朋友做了个采集程序

以www.xxxx.com/shop_list.php?page=1&province=%B1%B1%BE%A9为例

%B1%B1%BE%A9是gb2312的转码,例如

$aa=”北京”;
$aa = @iconv(“utf-8″, “gb2312″,$aa);
echo $bb=urlencode($aa);

我们通过file_get_contents($url) 抓取网页 当然也可以是curl

function getHtml($url){
$ch2 = curl_init($url);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($ch2);
curl_close($ch2);
return $html;
}

抓取我们想要的页面数据,可以设定从哪个位置到哪个位置的区间,取出中间数据,通过以下方法实现

function findneed($wholestr,$strkey1,$strkey2)
{
$num1 = strpos($wholestr , $strkey1)+strlen($strkey1);
$num2 = strpos($wholestr ,$strkey2);
$needstr =substr($wholestr ,$num1,$num2-$num1 );
return $needstr;
}
当然这是一种方法,我们只要写出一个php即可,根据分页抓取,但是如果都放在循环里面,岂不是很慢

我们介绍另个算法

<script><br /> location.href=&rdquo;index.php?page=<?=$page?>&provinceIndex=<?=$provinceIndex?>&totalPage=<?=$totalPage?>&rdquo;;<br /> </script>

通过实现网页跳转页数,抓取,访问程序,不断跳转页数,把当前url的page 数组保存到数据库

其他的无非是些正则表达式的用法:

比如我们想取页面中的所有城市

province

可用preg_match_all(‘/

(.*?)表示任意字符   . 是任何东西 * 是0至无限  ? 是0至1

还有种算法是递归,类似循环取值

function collectionProvinceData($url,$province,$page=1,$totalPage=-1){
if($page>$totalPage&&$totalPage>-1){
return false;
}
$collectionUrl = $url."?page=".$page."&province=".urlencode(iconv('UTF-8', 'GB2312', $province));
echo "当前url:".$province."第{$page}页 url".$collectionUrl."


";
$html = getHtml($collectionUrl);
$html = mb_convert_encoding($html, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5');
if($totalPage==-1){
$latestPageNum = getLatestPageNum($html);
if($latestPageNum>0){
$totalPage = $latestPageNum;
}
}
$dataRows = getDataRows($html);
saveDataRowsOrNot($dataRows);
if(!empty($dataRows)){
$page++;
}
ob_flush();
flush();
collectionProvinceData($url,$province,$page,$totalPage);
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn