gpt4 book ai didi

html - XPath 选择两个标题之间的所有元素?

转载 作者:可可西里 更新时间:2023-11-01 12:59:11 25 4
gpt4 key购买 nike

<h2>Headline 1</h2>
<p>some text</p>
<p>some more text</p>
<ul>
<li>list item 1</li>
<li>list item 2</li>
</ul>
<p>more text</p>
<h2>Headline 2</h2>

我在网页中有上述内容,我希望能够定位第一个 h2 之后的所有元素,其中包含文本 'Headline 1' up to but NOT包括包含文本 'Headline 2' 的元素 h2

我可以这样定位元素:

//*[count(preceding-sibling::hr)=1]

但这并不特定于包含的文本,因此如果页面发生变化,则 xpath 可能指向完全不同的内容。

我想要的 sudo 代码术语是这样的:

give me all the elements between the header 'Headline 1' and the header 'Headline 2' including 'Headline 1'

这有可能吗?

最佳答案

这个 XPath,

//*[    preceding-sibling::h2[. = 'Headline 1'] 
and following-sibling::h2[. = 'Headline 2']]

将选择字符串值为 'Headline 1''Headline 2'h2 之间的所有元素:

<p>some text</p>
<p>some more text</p>
<ul>
<li>list item 1</li>
<li>list item 2</li>
</ul>
<p>more text</p>

Andersson 在评论中指出,OP 希望第一个 h2 包含在选择中。

Andersson 最初的想法是可行的:

//h2[. = 'Headline 1'] |
//*[ preceding-sibling::h2[. = 'Headline 1']
and following-sibling::h2[. = 'Headline 2']]

另一种方式:

//*[self::h2[. = 'Headline 1']
or ( preceding-sibling::h2[. = 'Headline 1']
and following-sibling::h2[. = 'Headline 2']]

或者,可能是理想的方式:

//h2[. = 'Headline 2']
/preceding-sibling::*[not(following-sibling::h2[. = 'Heading 1'])]

因为它避免了必须指定两次 'Heading 1'

关于html - XPath 选择两个标题之间的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43122455/

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