【问题标题】:XPath to select between two HTML comments is not working?在两个 HTML 注释之间进行选择的 XPath 不起作用?
【发布时间】:2013-10-29 16:17:59
【问题描述】:

我正在尝试在两个 HTML cmets 之间选择一些内容,但在正确处理时遇到了一些问题(如“XPath to select between two HTML comments?”中所示)。 当新的 cmets 在同一行时似乎有问题。

我的 HTML:

<html>
 ........
 <!-- begin content -->
 <div>some text</div>
 <div>
   <p>Some more elements</p>
 </div>
 <!-- end content --><!-- begin content -->
 <div>more text</div>
 <!-- end content -->
 .......
</html>

我用:

doc.xpath("//node()[preceding-sibling::comment()[. = ' begin content ']]
          [following-sibling::comment()[. = ' end content ']]")

结果:

<div>some text</div>
<div>
  <p>Some more elements</p>
</div>
<!-- end content --><!-- begin content -->
<div>more text</div>

我想得到什么:

<div>some text</div>
<div>
  <p>Some more elements</p>
</div>

【问题讨论】:

    标签: html ruby xpath nokogiri scraper


    【解决方案1】:

    如果你对第一对cmets感兴趣,可以先找第一条评论:

    //comment()[.=' begin content ']/following::*[not(preceding::comment()[.=' end content '])]
    

    即:

    //comment()[1][.=' begin content ']           <-- look for first suitable comment
        /following::*                             <-- take all following nodes
             [not(preceding::comment()[.=' end content '])] <-- satisfying condition there is no preceding "end comment"
    

    【讨论】:

      猜你喜欢
      • 2011-12-24
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      • 2011-04-27
      • 1970-01-01
      相关资源
      最近更新 更多