Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

<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"

like image 230
Piotr Müller Avatar asked Jun 07 '13 10:06

Piotr Müller


People also ask

How do you get to the nth sub element using the xpath?

By adding square brackets with index. By using position () method in xpath.

How do you select the second element with the same 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.

How do you find the nth element?

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.


1 Answers

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.

like image 166
choroba Avatar answered Oct 13 '22 04:10

choroba