我制作了这个简单的 PHP 网络爬虫,它从开始的 body 标记之后的页面获取源代码,剥离其他 HTML 标记,然后回显内容。
当我启动它给它一个以 .html 结尾的页面时它会起作用,但是当我将一个 URL 像 URL 提供给来自 Google 的一组结果时,它不会跟随这些链接并获取内容并回显内容。
我怎样才能让它跟随谷歌搜索结果的 URL 并跟随其中的链接并回显其内容?
下面是爬虫的代码:
error_reporting( E_ERROR );
define( "CRAWL_LIMIT_PER_DOMAIN", 50 );
$domains = array();
$urls = array();
$dom = new DOMDocument();
$matches = array();
function crawl( $domObject, $url, $matchList )
{
global $domains, $urls;
$parse = parse_url( $url );
$domains[ $parse['host'] ]++;
$urls[] = $url;
$content = file_get_contents( $url );
if ( $content === FALSE ){
return;
}
$content = stristr($content, "<body>");
$domObject->loadHTML($content);
$anchors = $domObject->getElementsByTagName('a');
foreach($anchors as $anchor){
if(preg_match('/(?:https?:\/\/|www)[^\'\" ]*/i', (string)($anchor->getAttribute('href')))){
array_push($matchList, (string)($anchor->getAttribute('href')));
}
else{
preg_match('/(?:https?:\/\/|www)[^\/]+(?:\S*?\/)*/i', $url, $beginings);
$urlPrefix = $beginings[0];
$absolute = (string)(((string)$urlPrefix).((string)$anchor->getAttribute('href')));
array_push($matchList, $absolute);
}
}
echo strip_tags($content) . "<br /><br /><br />";
foreach( $matchList as $crawled_url ) {
$parse = parse_url( $crawled_url );
if ( count( $domains[ $parse['host'] ] ) < CRAWL_LIMIT_PER_DOMAIN && !in_array( $crawled_url, $urls ) ) {
sleep( 1 );
crawl( $domObject, $crawled_url, $matchList );
}
}
}
crawl($dom, 'http://www.google.com/search?q=google', $matches);