查看文章 |
用PHP采集网页数据的方法2008-06-11 14:09:37 作者:编辑整理 来源:LaoGe.Info
内容简介:数据抓取,以前一直以为是非常深奥的学问。找出页面的所有的链接,可以嵌套查找其它链接的页面,再对href中的内容进行分析,同样用preg_match 来判断是不是这个域名下的内容。
preg_match_all("/<[aA][[:space:]][hH][rR][eE][fF]=\"([^\"]+)\"[^>]+>(.*)<\/[aA]>/", $content , $arrAddress ); 找出页面的所有的链接,可以嵌套查找其它链接的页面,再对href中的内容进行分析,同样用preg_match 来判断是不是这个域名下的内容。 接下来可以是文件操作,也可以是数据库操作。 核心的代码如下: function _unique_hrefs( &$content ) { if( $this -> _debug == true ) { print( __LINE__.' Parse unique hrefs <br>' ); $this -> _scrollDown( ); }
$addr = null; $port = null;
if( empty( $content ) == false ) { if( $this -> _debug == true ) { print( __LINE__.' Parse: Parsing content <br>' ); $this -> _scrollDown( ); }
preg_match_all("/<[aA][[:space:]][hH][rR][eE][fF]="([^"]+)"[^>]+>(.*)</[aA]>/", $content , $arrAddress );
if( empty( $arrAddress[1] ) == false ) {
if( $this -> _debug == true ) { print( __LINE__.' <b>Found not identified hrefs</b> <br>' ); $this -> _scrollDown( ); print( '---------------------------<br>' ); $this -> _scrollDown( ); }
foreach( $arrAddress[1] AS $id => $href ) { $href = eregi_replace( $this -> _url , '' , $href );
if( !eregi( 'http|www|mailto', $href ) &&$href!="#" &&!eregi( 'javascript|;', $href ) ) {
if( $this -> _debug == true ) { if( !isset( $this -> _unique_hrefs[$href] ) ) { $this -> _unique_hrefs[$href]['href'] = $href; $this -> _unique_hrefs[$href]['name'] = $arrAddress[2][$id]; $this -> _unique_hrefs[$href]['visit'] = 0; if( $this -> _debug == true ) { print( __LINE__.' Parse: Editing _unique_hrefs, making : '.htmlentities( strip_tags( $href ) ).' <br>' ); $this -> _scrollDown( ); } } else {
if( $this -> _debug == true ) { print( __LINE__.' Parse: Href exitst at _unique_hrefs, breaking : '.htmlentities( strip_tags( $href ) ).' <br>' ); $this -> _scrollDown( ); }
} } } else { //*********************** // //your code here.. // //*********************** if( $this -> _debug == true ) { print( __LINE__.' Parse: bad href expresion, breaking : '.htmlentities( strip_tags( $href ) ).' <br>' ); $this -> _scrollDown( ); } } }
if( $this -> _debug == true ) { print( '---------------------------<br>' ); $this -> _scrollDown( ); }
} } } |