【问题标题】:PHP Web Crawler doesn't crawl .php filesPHP Web Crawler 不抓取 .php 文件
【发布时间】:2015-09-21 06:10:38
【问题描述】:

这是我尝试构建的简单网络爬虫

<?php

    $to_crawl = "http://samplewebsite.com/about.php";

    function get_links($url)
    {
        $input = @file_get_contents($url);
        $regexp = " <a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a> ";
        preg_match_all("/$regexp/siU", $input, $matches);

        $l = $matches[2];

        foreach ($l as $link) {
            echo $link."</br>";
        }
    }


    get_links($to_crawl);


?>

当我尝试运行脚本并将 $to_crawl 变量设置为以文件名结尾的 url 时,例如“facebook.com/about”,它可以工作,但由于某种原因,当链接以“.php”文件名结尾时,它只是回显什么。有人可以帮忙吗?

【问题讨论】:

  • 你能在浏览器中得到那个链接的结果吗?
  • 是的,它工作得很好,我把它放在我的 python 编写的网络爬虫中,它工作得很好。
  • 试试$regexp = "\\s*&lt;a\\s+[^&gt;]*href=(\"??)([^\" &gt;]*?)\\1[^&gt;]*&gt;(.*)&lt;\/a&gt;\\s*";。另外,您是否考虑使用 DOMDocument?您似乎只是收集带有内部文本的&lt;a&gt; 标签href URL。对吗?
  • 正确,我不知道 DOMDocument 是什么,对不起,会更容易吗?谢谢你,你对我的 $regexp 的编辑工作了 :)
  • @SamirChahine:我发布了一个关于如何利用 DOMDocument + DOMXPath 的示例的答案,我认为这是从网页中抓取任何信息的最佳工具组合。特别是如果您只需要来自特定节点/属性的文本。正则表达式对于任意 HTML 代码来说太不安全了。

标签: php regex web-crawler


【解决方案1】:

要获取所有链接及其内部文本,您可以像这样使用DOMDocument

$dom = new DOMDocument;
@$dom->loadHTML($input);                    // Your input (HTML code)

$xp = new DOMXPath($dom);
$links = $xp->query('//a[@href]');          // XPath to get only <a> tags with a href attribute

$result = array();
foreach ($links as $link) {
    $result[] = array($link->getAttribute("href"), $link->nodeValue);
}
print_r($result);

IDEONE demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 2011-12-21
    相关资源
    最近更新 更多