【问题标题】:Using Simple Html Dom to extract bold text from a div使用 Simple Html Dom 从 div 中提取粗体文本
【发布时间】:2017-02-20 05:30:39
【问题描述】:

从事一个脚本项目,实际上花了最后 4 个小时来研究我能做的所有事情 - 我的脑袋在这件事上真的不再起作用了,真的需要你的帮助。

所以我有一个从网站抓取数据的 PHP cURL 脚本。我可以抓取具有 ID 的 div 和所有这些。但是,我如何从没有任何 ID/类/或任何特定内容的 DIV 中获取特定文本,除了它是 div 中唯一的粗体项目这一事实?

这是网站上的 HTML 文本:

<div class="firststyle"><label for="calculator" class="class-coll-1">
                <p class="sr-only">Welcome to the calculator:</p> <b>What is one plus two?</b> </label></div>

我试图从这个 HTML 部分解析/提取的只是文本“什么是一加二?”。 如何定义这个特定的部分被选中?

我目前唯一能做的就是使用以下脚本解析整个 div:

$html = str_get_html($response);
$the_question = $html->find('div[class=firststyle]');

但是,这会得到所有文本,包括我不需要的“欢迎使用计算器”标签。

是否有可能以某种方式将解析后的数据保存到一个变量中,然后使用不同的脚本从该变量中提取数据?

或者我可以这样做:

查找具有此 ID 的 div -> 在其中查找粗体文本

或许:

找到带有 ID 的 div -> 取出文字“欢迎使用计算器”

【问题讨论】:

    标签: php html curl simple-html-dom


    【解决方案1】:
    echo $html->find('.firststyle b', 0)->innertext;
    #=> What is one plus two?
    

    【讨论】:

      【解决方案2】:

      如果你有来自网站的 HTML,你可以使用 DOMDocument 类来解析它。

      $html = file_get_contents('http://www.example.com');
      
      $dom = new DOMDocument();
      $dom->loadHTML($html);
      

      DOMDocument 类附带了很多方法。这是您将需要的两个getElementByIdgetElementsByTagName

      类似这样的:

      $html = '<div id="test"><b>I want to be found!</b></div><div id="poep"><b>Im not selected</b></div>';
      
      $dom = new DOMDocument();
      $dom->loadHTML($html);
      
      $div = $dom->getElementById('test');
      $text = $div->getElementsByTagName('b')->item(0)->nodeValue;
      
      echo $text;
      

      将输出:

      I want to be found!
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-09
        • 1970-01-01
        • 1970-01-01
        • 2013-07-22
        • 1970-01-01
        • 2012-04-08
        • 2013-05-07
        • 2018-05-11
        相关资源
        最近更新 更多