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"
By adding square brackets with index. By using position () method in xpath.
For example if both text fields have //input[@id='something'] then you can edit the first field xpath as (//input[@id='something'])[1] and the second field's xpath as (//input[@id='something'])[2] in object repository.
The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With