Reputation: 5558
We can use :position() in xpath to retreive nth element in simple HTML block like this:
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
</ul>
We can query element by //li[position()=2]
but this won't work in this situation:
<ul>
<b><li>first</li></b>
<b><li>second</li></b>
<b><li>third</li></b>
</ul>
And we have to use //b[position()=2]/li
.
The problems is that I want to create a XPath rule for nth-element for my selenium test, which will no be tight coupled with decoarational tags. I need a XPath that will work even when mu nth-elements will be decorated with additional tags.
I know that for testing purposes I can change backend logic to provide additional testing handles in html like data-* attributes, but suppose that I can't change code of app under test.
So, I'm searching for XPath query like: "Give me third <li>
element, wherever it lays in specified page (or page block) even if it is multiply nested"
Upvotes: 6
Views: 9729
Reputation: 242038
Note that [position()=3]
can be shorthened to [3]
. The answer to your question then is
(//li)[3]
The position is related to the nodelist returned by the parentheses.
Upvotes: 15