XPath在两个HTML注释之间进行选择?

xec*_*ner 6 html ruby xpath nokogiri scraper

我有一个很棒的HTML页面.但我想使用Xpath选择某些节点:

<html>
 ........
<!-- begin content -->
 <div>some text</div>
 <div><p>Some more elements</p></div>
<!-- end content -->
.......
</html>
Run Code Online (Sandbox Code Playgroud)

我可以在<!-- begin content -->使用后选择HTML :

"//comment()[. = ' begin content ']/following::*" 
Run Code Online (Sandbox Code Playgroud)

我也可以在<!-- end content -->使用之前选择HTML :

"//comment()[. = ' end content ']/preceding::*" 
Run Code Online (Sandbox Code Playgroud)

但是,我必须让XPath选择两条评论之间的所有HTML吗?

Jus*_* Ko 17

我会寻找前面有第一条评论的元素,然后是第二条评论:

doc.xpath("//*[preceding::comment()[. = ' begin content ']]
              [following::comment()[. = ' end content ']]")
#=> <div>some text</div>
#=> <div>
#=>   <p>Some more elements</p>
#=> </div>
#=> <p>Some more elements</p>
Run Code Online (Sandbox Code Playgroud)

请注意,上面给出了介于两者之间的每个元素.这意味着如果迭代每个返回的节点,您将获得一些重复的嵌套节点 - 例如"更多元素".

我想你可能实际上想要在两者之间获得顶级节点 - 即评论的兄弟姐妹.这可以使用preceding/following-sibling替代来完成.

doc.xpath("//*[preceding-sibling::comment()[. = ' begin content ']]
              [following-sibling::comment()[. = ' end content ']]")
#=> <div>some text</div>
#=> <div>
#=>   <p>Some more elements</p>
#=> </div>
Run Code Online (Sandbox Code Playgroud)

更新 - 包括评论

//*仅使用返回元素节点,其中不包含注释(以及其他一些注释).你可以改变*node()返回的一切.

puts doc.xpath("//node()[preceding-sibling::comment()[. = 'begin content']]
                        [following-sibling::comment()[. = 'end content']]")
#=> 
#=> <!--keywords1: first_keyword-->
#=> 
#=> <div>html</div>
#=> 
Run Code Online (Sandbox Code Playgroud)

如果您只想要元素节点和注释(即不是所有内容),您可以使用self轴:

doc.xpath("//node()[self::* or self::comment()]
                   [preceding-sibling::comment()[. = 'begin content']]
                   [following-sibling::comment()[. = 'end content']]")
#~ #=> <!--keywords1: first_keyword-->
#~ #=> <div>html</div>
Run Code Online (Sandbox Code Playgroud)