【问题标题】:Can only get one result Dom Crawler只能得到一个结果 Dom Crawler
【发布时间】:2018-05-13 01:27:30
【问题描述】:

试图在 div id=firehoselist 中获取 h2 中的所有内容(以获取文章的标题),但以下代码仅返回第一个结果。有什么想法欢迎

    $crawler = new Crawler($content);

    $crawler->filterXPath('//div[@id="firehoselist"]//*')->each(function (Crawler $node) use (&$results) {

        $results[] = trim($node->filter('h2')->text());

 });

我要抓取的内容太乱,无法在此处发布,但它来自 slashdot org 网站

【问题讨论】:

    标签: symfony dom domcrawler


    【解决方案1】:

    //div[@id="firehoselist"] 正在寻找 ID 为 firehoselist每个 元素,并且只会获得此条目 $node->filter('h2')->text()first 结果。

    您需要得到每个 #firehoselist h2 的已解析html:

    $crawler->filterXPath('//div[@id="firehoselist"]//h2')->each(function (Crawler $node) use (&$results) {
    
            $results[] = trim($node->text());
    
     });
    

    【讨论】:

    • Coolio 谢谢 - 也只需要一个额外的 / 就可以像 $crawler->filterXPath('//div[@id="firehoselist"]//h2')->each(function (Crawler $node) 使用 (&$results) {
    • 我突然想到我实际上想同时让其他元素循环,而不仅仅是 H2 - 尝试不同的组合但无法解决
    • 我想'//div[@id="firehoselist"]//* 会为您提供具有此 ID 的容器的所有元素。你试过了吗?
    • 确实获得了内容,但现在我不知道如何获得 H2 值 - 为什么不 $node->filter('h2')->text();返回错误'当前节点列表为空'
    • 这个错误意味着你没有h2元素。只需打印内部,看看你有什么。
    猜你喜欢
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 2020-04-28
    • 1970-01-01
    相关资源
    最近更新 更多