【发布时间】:2013-05-17 01:02:10
【问题描述】:
我制作了这个简单的 PHP 网络爬虫,它从开始的 body 标记之后的页面获取源代码,剥离其他 HTML 标记,然后回显内容。
当我启动它给它一个以 .html 结尾的页面时它可以工作,但是当我将一个 URL 像 URL 提供给一组来自 Google 的结果时,它不会跟随这些链接并获取内容并回显内容。
如何让它跟随 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);
【问题讨论】:
-
首先,将
$content = stristr($content, "<body>");更改为$content = stristr($content, "<body");- 标签有时包含属性,例如<body class="hp"...> -
另外,请遵循以下“Kohjah Breese”的建议。如果您正在抓取 Google,预计会有限制 :)
-
@Gor 啊,好的。我忘记了body标签中的属性。谢谢。
-
没问题。很高兴能提供帮助。
标签: php web-crawler