How to select Nth element in XPath with multilevel nesting


We can use :position() in xpath to retreive nth element in simple HTML block like this:


We can query element by //li[position()=2] but this won't work in this situation:


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"

Best Solution

Note that [position()=3] can be shorthened to [3]. The answer to your question then is


The position is related to the nodelist returned by the parentheses.