【问题标题】:Simple HTML DOM gets only 1 element简单的 HTML DOM 仅获得 1 个元素
【发布时间】:2011-09-22 21:04:28
【问题描述】:

我在这里关注 NetTuts 的一个简化版的抓取教程,它基本上可以找到所有带有 class=preview 的 div

http://net.tutsplus.com/tutorials/php/html-parsing-and-screen-scraping-with-the-simple-html-dom-library/comment-page-1/#comments

这是我的代码。问题是当我数 $items 时,我只得到 1,所以它只得到第一个带有 class=preview 的 div,而不是全部。

$articles = array();   
$html = new simple_html_dom();
$html->load_file('http://net.tutsplus.com/page/76/');

$items = $html->find('div[class=preview]');  
echo "count: " . count($items);

【问题讨论】:

  • 建议的第三方替代 SimpleHtmlDom 实际使用 DOM 而不是字符串解析:phpQueryZend_DomQueryPathFluentDom
  • 如果你做了$items[] = $html->find('div[class=preview]'); 或者只是先声明了数组。它要么没有正确地抓取 DOM,要么没有正确地存储它。也许试试var_dump($html->find('div[class=preview]'))
  • 您可以比较 simplehtmldom phpquery 和 ganon here 的选择语法。我发现 phpquery 的语法最简洁,总体上是最好的。

标签: php web-scraping simple-html-dom


【解决方案1】:

尝试使用DOMDocumentDOMXPath

$file = file_get_contents('http://net.tutsplus.com/page/76/');
$dom = new DOMDocument();
@$dom->loadHTML($file);
$domx = new DOMXPath($dom);
$nodelist = $domx->evaluate("//div[@class='preview']");
foreach ($nodelist as $node) { print $node->nodeValue; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 2015-08-07
    • 2020-10-24
    • 1970-01-01
    相关资源
    最近更新 更多