Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

html - XPath to select all elements between two headings?

<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>

I have the above in a webpage and I want to be able to target all elements following the first h2 that contains the text 'Headline 1' up to but NOT including the element h2 that contains the text 'Headline 2'.

I can target the elements like this:

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

but this is not specific to the text contained and so if the page ever changed then the xpath could be pointing to something totally different.

What I would like in sudo code terms is this:

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

Is this at all possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This XPath,

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

will select all elements between h2s with string values of 'Headline 1' and 'Headline 2':

<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 points out in the comments that OP wants the first h2 included in the selection.

Andersson's initial thought would work:

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

Here's another way:

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

Or, probably the ideal way:

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

because it avoids having to specify 'Heading 1' twice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...