【问题标题】:PHP web crawler, check URL for pathPHP网络爬虫,检查URL路径
【发布时间】:2015-07-28 16:00:37
【问题描述】:

我正在编写一个简单的网络爬虫来抓取网站中的一些链接。 我需要检查返回的链接,以确保我有选择地收集我想要的。

例如,这里有几个从http://www.polygon.com/返回的链接

[0]http://www.polygon.com/2015/5/15/8613113/destiny-queens-wrath-bounties-ether-key-guide#comments

[1]http://www.polygon.com/videos

[2]http://www.polygon.com/2015/5/15/8613113/destiny-queens-wrath-bounties-ether-key-guide

[3]http://www.polygon.com/features

所以链接 0 和 2 是我想要抓取的链接,1 和 3 我们不想要。链接之间有明显的视觉区别,那么我将如何比较它们?

如何检查以确保不返回 1 和 3?理想情况下,我希望能够输入一些东西,以便它可以适应任何网站。

我想我需要检查链接以确保它过去 /2015/ 等,但我很迷茫。

这是我用来抓取链接的 PHP 代码:

<?php

$source_url = 'http://www.polygon.com/';
$html = file_get_contents($source_url);
$dom = new DOMDocument;
@$dom->loadHTML($html);
$links = $dom->getElementsByTagName('a');

foreach ($links as $link) {
    $input_url = $link->getAttribute('href');
    echo $input_url . "<br>";   
}
?>

【问题讨论】:

  • 一个简单的strpos($input_url, '/2015/') &gt;= (strlen($source_url)-1) 就可以解决问题吗?

标签: php url path web-crawler bots


【解决方案1】:

看起来正则表达式在这里会有所帮助。 例如,您可以说:

/* if $input_url contains a 4 digit year, slash, number(s), slash, number(s) */
if (preg_match("/\/20\d\d\/\d+\/\d+\/",$input_url)) {
  echo $input_url . "<br>";
}

【讨论】:

    猜你喜欢
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多