天天看点

使用PHP做网页采集实例过程总结

查看原文:​​http://www.sijitao.net/1511.html​​

​ 最近有个任务是需要我检查一些网站,如果纯手工检查的话,感觉既费时又无聊。所以我就想用采集。思路其实很简单,先把网站的源码采集下来,然后用正则表达式去匹配符合的链接,最后把标题和网址入库、分析。因为我使用最多的是php,所以打算用php做网页采集。

第一步,链接数据库,取出需要检查的网站和正则。

数据库这里我用了postgresql,数据库和表已经按要求建好。因为默认配置的环境是centos系统加nginx、mysql和php,所以首先是配置环境。配置具体不在这里多说,下次总结。环境配置好后在php中用pg_connect连接数据库,这里我连接了两个不同的数据库。

[code language="php"]
 $conn_1=pg_connect("host=xxx.xxx.xxx.xxx port=5432 dbname=mydb1 user=postgres password=xxxxxx") ;
 $conn_2=pg_connect("host=xxx.xxx.xxx.xxx port=5432 dbname=mydb2 user=postgres password=xxxxxx") ;
 [/code]      

第二步,取出网页源码,对源码进行初步处理。

不同网站编码格式不一样,需要先把编码统一转换成utf-8,不然之后入库会出现乱码。

[code language="php"]
//获取网页源码
 //$url='http://www.sijitao.net/' ;
 $str = file_get_contents($url);
 //使用preg_match和正则表达式取出编码
 $wcharset = preg_match("/<meta.+?charset=[^\w]?([-\w]+)/i",$str,$temp) ? strtolower($temp[1]):"" ;
 //编码转换
 if($wcharset){
 $str=iconv("$wcharset", "UTF-8", $str) ;
 }[/code]      

这里我还使用str_ireplace()函数对取到的源码做了些字符替换,不然最后用正则匹配网址的时候会出现问题。

第三步,匹配处理后的源码字符串,对匹配的数据入库。

[code language="php"]
$pat = "/<a(.*?)href=\"($preg)\"(.*?)>(.*?)<\/a>/is";
 preg_match_all($pat, $str, $m);
 $cnt=count($m[2]) ;
 for($i=0;$i<$cnt;$i++){
 if(strip_tags($m[2][$i])){
 $url=strip_tags($m[2][$i]) ;
 $url=$m[2][$i] ;
 }
 if(strip_tags($m[4][$i])){
 $title=strip_tags($m[4][$i]) ;
 }
 else{
 $title="There's Something Errors!" ;
 }
 //编写代码,对title和url进行入库操作。
 }
 }