【问题标题】:How to scrape html contents of one div by id using php如何使用 php 通过 id 抓取一个 div 的 html 内容
【发布时间】:2013-08-08 10:39:46
【问题描述】:

我想从我的另一个域中抓取一个 div 的页面包含:

<div id="thisone">
    <p>Stuff</p>
</div>

<div id="notthisone">
    <p>More stuff</p>
</div>

使用这个 php...

<?php
    $page = file_get_contents('http://thisite.org/source.html');
    $doc = new DOMDocument();
    $doc->loadHTML($page);
    foreach ($doc->getElementsByTagName('div') as $node) {
        echo $doc->saveHtml($node), PHP_EOL;
    }
?>

...给我http://thisite.org/source.html 上的所有 div,带有 html。但是,我只想通过 id 为“thisone”的 div,但使用:

foreach ($doc->getElementById('thisone') as $node) {

什么都没有。

【问题讨论】:

    标签: php html web-scraping scrape


    【解决方案1】:
    $doc->getElementById('thisone');// returns a single element with id this one
    

    尝试$node=$doc-&gt;getElementById('thisone');,然后打印$node

    顺便说一句,您可以将 phpQuery 用于类似 jquery 的语法:pq("#thisone")

    【讨论】:

      【解决方案2】:

      $doc-&gt;getElementById('thisone') 返回单个 DOMElement,而不是数组,因此您无法遍历它

      就这样吧:

      $node = $doc->getElementById('thisone');
      echo $doc->saveHtml($node), PHP_EOL;
      

      【讨论】:

        【解决方案3】:

        看PHP手册http://php.net/manual/en/domdocument.getelementbyid.php getElementByID 返回一个元素或 NULL。不是数组,因此您不能对其进行迭代。

        改为这样做

        <?php
            $page = file_get_contents('example.html');
            $doc = new DOMDocument();
            $doc->loadHTML($page);
            $node = $doc->getElementById('thisone');
             echo $doc->saveHtml($node), PHP_EOL;
        ?>
        

        在运行中 php edit.php 你会得到这样的东西

        <div id="thisone">
              <p>Stuff</p>
          </div>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-08-09
          • 1970-01-01
          • 2017-04-17
          • 2023-04-02
          • 2023-03-17
          • 2020-04-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多