【问题标题】:Simple HTML DOM Parser - Get all plaintex rather than text of certain element简单的 HTML DOM 解析器 - 获取所有纯文本而不是某些元素的文本
【发布时间】:2013-04-28 16:42:30
【问题描述】:

我尝试了question 上发布的所有解决方案。虽然它与我的问题相似,但它的解决方案对我不起作用。

我正在尝试获取<b> 之外的纯文本,它应该在<div id="maindiv> 之内。

<div id=maindiv>
     <b>I don't want this text</b>
     I want this text
</div>

$part 是包含&lt;div id="maindiv"&gt; 的对象。 现在我尝试了这个:

$part->find('!b')->innertext;

上面的代码不起作用。当我尝试这个时

$part-&gt;plaintext;

它返回了像这样的所有纯文本

I don't want this text I want this text

我阅读了官方文档,但没有找到任何解决此问题的方法:

【问题讨论】:

    标签: php parsing dom html-parsing web-scraping


    【解决方案1】:

    查询:

    $selector->query('//div[@id="maindiv"]/text()[2]')
    

    解释:

    //               - selects nodes regardless of their position in tree
    
    div              - selects elements which node name is 'div'
    
    [@id="maindiv"]  - selects only those divs having the attribute id="maindiv"
    
    /                - sets focus to the div element
    
    text()           - selects only text elements
    
    [2]              - selects the second text element (the first is whitespace)
    
                       Note! The actual position of the text element may depend on
                       your preserveWhitespace setting.
    
                       Manual: http://www.php.net/manual/de/class.domdocument.php#domdocument.props.preservewhitespace
    

    例子:

    $html = <<<EOF
    <div id="maindiv">
         <b>I dont want this text</b>
         I want this text
    </div>
    EOF;
    
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    
    $selector = new DOMXpath($doc);   
    
    $node = $selector->query('//div[@id="maindiv"]/text()[2]')->item(0);
    echo trim($node->nodeValue); // I want this text
    

    【讨论】:

    • 比您的快速回复,请您为我解释一下。
    【解决方案2】:

    先删除&lt;b&gt;

    $part->find('b', 0)->outertext = '';
    echo $part->innertext; // I want this text
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 2020-03-02
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 2015-02-26
      相关资源
      最近更新 更多