【问题标题】:Goutte - dom crawler - remove nodeGoutte - dom 爬虫 - 移除节点
【发布时间】:2014-12-08 09:34:07
【问题描述】:

我的网站上有 html (http://testsite.com/test.php):

<div class="first">
  <div class="second">
     <a href="/test.php">click</a>
     <span>back</span>
  </div>
</div>
<div class="first">
  <div class="second">
     <a href="/test.php">click</a>
     <span>back</span>
  </div>
</div>

我想收到:

<div class="first">
  <div class="second">
     <a href="/test.php">click</a>
  </div>
</div>
<div class="first">
  <div class="second">
     <a href="/test.php">click</a>
  </div>
</div>

所以我想删除跨度。 我基于http://symfony.com/doc/current/components/dom_crawler.html 在 Symfony2 中使用 Goutte:

    $client = new Client();
    $crawler = $client->request('GET', 'http://testsite.com/test.php');

    $crawler->filter('.first .second')->each(function ($node) {
        //??????
    });

【问题讨论】:

    标签: php symfony dom web-crawler goutte


    【解决方案1】:

    作为explained in the docs:

    DomCrawler 组件简化了 HTML 和 XML 文档的 DOM 导航。

    还有:

    尽管可能,DomCrawler 组件并非设计用于操作 DOM 或重新转储 HTML/XML。

    DomCrawler 旨在从 DOM 文档中提取详细信息,而不是对其进行修改。

    但是...

    由于 PHP 通过引用传递对象,而 Crawler 基本上是 DOMNodes 的包装器,因此在技术上可以修改底层 DOM 文档:

    // will remove all span nodes inside .second nodes
    $crawler->filter('html .content h2')->each(function (Crawler $crawler) {
        foreach ($crawler as $node) {
            $node->parentNode->removeChild($node);
        }
    });
    

    这是一个工作示例:https://gist.github.com/jakzal/8dd52d3df9a49c1e5922

    【讨论】:

    • 它抛出未定义变量的错误:爬虫,然后我有使用($crawler),但它对我不起作用
    • 对我也不起作用。为了改进答案,我建议将 $node 从闭包中消除歧义,将 $nodeforeach() 中消除歧义。我收到 ig Error: Call to a member function removeChild() on null 的错误。解决此问题并且示例有效后,很高兴为您投票。
    • 虽然您的 gist 示例正在运行,但此示例不是由于上述参数问题。
    • 不知道那里发生了什么。用正确的例子更新了我的答案。干杯!
    【解决方案2】:

    To remove a node the anonymous function must return false.

    只要在reducer内部返回false,$node就会被删除。

    【讨论】:

    • reducer 内部,而不仅仅是任何闭包。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2010-11-25
    • 1970-01-01
    • 2019-11-07
    • 2011-11-04
    相关资源
    最近更新 更多