【问题标题】:DOMCrawler not dumping data properly for parsingDOMCrawler 未正确转储数据以进行解析
【发布时间】:2015-05-29 19:43:37
【问题描述】:

我正在使用 Symfony、Goutte 和 DOMCrawler 来抓取页面。不幸的是,这个页面有许多老式的数据表,没有 ID 或类或识别因素。所以我试图通过解析从请求中返回的源代码来找到一个表,但我似乎无法访问任何信息

我认为当我尝试过滤它时,它只过滤第一个节点,这不是我想要的数据所在的位置,所以它什么也不返回。

所以我有一个$crawler 对象。我试图通过以下循环得到我想要的:

$title = $crawler->filterXPath('//td[. = "Title"]/following-sibling::td[1]')->each(funtion (Crawler $node, $i) {
        return $node->text();
});

我不确定Crawler $node 是什么,我只是从网页上的示例中得到的。也许如果我能让这个工作正常,那么它将遍历$crawler 对象中的 each 节点并找到我真正想要的东西。

以下是页面示例:

<table> 
<tr>
    <td>Title</td>
    <td>The Harsh Face of Mother Nature</td>
   <td>The Harsh Face of Mother Nature</td>
</tr>
.
.
.
</table>

这只是一张桌子,这张桌子外面有很多桌子和一团乱七八糟的乱七八糟的东西。有任何想法吗?

(注意:之前我能够对$crawler 对象应用过滤器以获取我需要的一些信息,然后我serialize() 得到信息,最后得到了一个字符串,这是有道理的。但我无法得到一个字符串再也不用了,不知道为什么。)

【问题讨论】:

    标签: php symfony web-scraping goutte domcrawler


    【解决方案1】:

    DomCrawler html() 函数不会根据函数描述转储整个 html:

    http://api.symfony.com/2.6/Symfony/Component/DomCrawler/Crawler.html#method_html

    它只返回它在你的情况下所做的第一个节点。

    您可以使用http://php.net/manual/en/domdocument.savehtml.php,因为 DomCrawler 是一组 SplObjectStorage 。

    $html = $crawler->getNode(0)->ownerDocument->saveHTML();
    

    【讨论】:

      【解决方案2】:

      如果您查看Crawler::html() 的源代码,您会看到它正在执行以下操作:

      $html = '';
      foreach ($this->getNode(0)->childNodes as $child) {
          $html .= $child->ownerDocument->saveHTML($child);
      }
      return $html;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-28
        • 2016-11-25
        • 2013-04-18
        • 2011-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多