How to select an Nth element in XPath with multi-level nesting

We can use: position () in xpath to return the nth element to a simple HTML block as follows:

<ul> <li>first</li> <li>second</li> <li>third</li> </ul> 

We can request the element //li[position()=2] , but this will not work in this situation:

 <ul> <b><li>first</li></b> <b><li>second</li></b> <b><li>third</li></b> </ul> 

And we must use //b[position()=2]/li .

The problem is that I want to create an XPath rule for the nth element for my selenium test, which will not be closely associated with descriptor tags . I need XPath, which will work even when mu n-elements are decorated with additional tags.

I know that for testing, I can change the backend logic to provide additional testing descriptors in html, such as data- * attributes, but suppose I cannot change the application test code.

So, I'm looking for an XPath query, for example: "Give me the third <li> element, wherever it is on the specified page (or page block), even if it is repeatedly nested"

+4
source share
1 answer

Note that [position()=3] can be shortened to [3] . Then the answer to your question:

 (//li)[3] 

The position is associated with the nodelist returned by brackets.

+12
source

Source: https://habr.com/ru/post/1485013/


All Articles