Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get element's index by xpath?

I've next structure :

<div id='list'>
   <div class='column'>aaa</div>
   <div class='column'>bbb</div>
   ...
   <div class='column'>jjj</div>
</div>

I was wonder if there is a ways to use XPath, and to write some query were I can get the index of the requested element within the "list" element.

I mean that I'll ask for location of class='column' where the text value is aaa and I'll get 0 or 1...

Thanks

like image 971
Igal Avatar asked May 13 '13 10:05

Igal


People also ask

How do you find the index of an element using XPath?

In index, we can write the expression of XPath with the braces, and then we can write the index outside into the braces. It is defined as per specific nodes within the node-set for XPath index by using selenium webdriver.

Can we use index in XPath?

We can select specific nodes within xpath node sets by index with Selenium webdriver. We can mention a specific node with the help of its index number enclosed in []. Let us have a look at the below html code for an element having children. The element with tagname ul has multiple child elements with tagname li.

Does XPath index start at 0 or 1?

Note also, index values in XPath predicates (technically, 'proximity positions' of XPath node sets) start from 1, not 0 as common in languages like C and Java.


2 Answers

You could just count the div elements preceding the element you're looking for:

count(div[@id = 'list']/div[@id = 'myid']/preceding-sibling::div)
like image 99
basilikum Avatar answered Oct 10 '22 02:10

basilikum


You can count the preceding siblings:

count(//div[@id="list"]/div[@id="3"]/preceding-sibling::*)
like image 37
choroba Avatar answered Oct 10 '22 02:10

choroba