gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:25:03 25 4
gpt4 key购买 nike

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

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

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

"//comment()[. = ' begin content ']/following::*" 

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

"//comment()[. = ' end content ']/preceding::*" 

但是我必须要有 XPath 才能选择两个评论之间的所有 HTML 吗?

最佳答案

我会寻找在第一个注释之前和在第二个注释之后的元素:

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>

请注意,上面为您提供了介于两者之间的每个 元素。这意味着如果您遍历每个返回的节点,您将获得一些重复的嵌套节点 - 例如“更多元素”。

我认为您实际上可能只想获取中间的顶级节点 - 即评论的兄弟节点。这可以使用 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>

更新 - 包括评论

使用 //* 只返回元素节点,不包括注释(和其他一些)。您可以将 * 更改为 node() 以返回所有内容。

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

如果你只想要元素节点和注释(即不是全部),你可以使用self轴:

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

关于html - 在两个 HTML 注释之间进行选择的 XPath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18871618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com