Reputation: 169
Lets say I have this html (ignore tags names):
<div>
<card>
<h2>1</h2>
</card>
<footer>
<p>text 1</p>
</footer>
</div>
<div>
<card>
<h2>2</h2>
</card>
<footer>
<p>text 2</p>
</footer>
</div>
<div>
<card>
<h2>3</h2>
</card>
<footer>
<p>text 2</p>
</footer>
</div>
and I want to select p tag that have an h2 value of 2 (I will select p with text 2)
if I use this expression //h2[text()="2"]/../following::footer/p
I will get 2 p tags.
How do I select only the p tag with cousin h2
value of 2
?
EDIT: Robbie Averill answer was the first to work, but you should check other answers they are very good too.
Upvotes: 1
Views: 179
Reputation: 111726
This XPath,
//div[card/h2="2"]/footer/p
will select footer/p
cousins of card/h2
elements with string values of 2
.
Upvotes: 1
Reputation: 52685
Try to use below XPath to select required element:
//card[h2="2"]/following-sibling::footer/p
Upvotes: 1
Reputation: 24425
You can navigate from the h2
matched up to the div
that contains the element you want, then target footer/p
elements from there:
//h2[text()="2"]/../../footer/p
Upvotes: 1