【问题标题】:Simple Web scraping PHP Xpath DOM简单的 Web 抓取 PHP Xpath DOM
【发布时间】:2012-11-09 17:02:34
【问题描述】:

我正在尝试学习网络抓取并使用此示例从页面中获取链接。有没有更好的方法来做到这一点,或者例如获得 h1 的最简单方法是什么?

$html = file_get_contents('page.html');

//parse the html into a DOMDocument
$dom = new DOMDocument();
@$dom->loadHTML($html);

//grab all the links on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
    $href = $hrefs->item($i);
    $url = $href->getAttribute('href');
    echo "<br />Link: $url";

}

【问题讨论】:

    标签: php dom xpath web-scraping


    【解决方案1】:

    没有必要在你的 expath 前面加上/html/body//a 应该可以正常工作。

    另外,我会使用 foreach 而不是 for 循环,但这主要是一种风格选择。

    【讨论】:

    • 使用 php 的 curl 函数和 domdocument 代替 file_get_contents 来抓取它既简单又强大
    猜你喜欢
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 2011-09-16
    • 2015-01-07
    相关资源
    最近更新 更多