Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath get element by index

Tags:

xml

xslt

xpath

I have the below xpath expression

//div[@class="post-content"]//img

which runs on a html page, scanning for images. The above query returns a lot of images but I only want the second in the list.

I have tried these with no luck:

//div[@class="post-content"]//img[1] and
//div[@class="post-content"]//img[position()=1]
like image 983
Thomas Avatar asked Apr 05 '12 08:04

Thomas


People also ask

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

XPath index is defined as per specific nodes within the node-set for index by using selenium webdriver. We can also mention the index-specific node with the help of a number of indexes enclosed by []. The tag name element UI contains multiple child elements with tag name as li.

Does XPath start 0 or 1?

Such usage is almost always a bug because in XPath, the index starts at 1 , not at 0 .


2 Answers

In XPath index starts from 1 position, therefore

//div[@class="post-content"]//img[2] 

should work correctly if you have to select each 2nd img in div[@class="post-content"]. If you have to select only 2nd img from all images that are in div[@class="post-content"], use:

(//div[@class="post-content"]//img)[2] 
like image 119
Kirill Polishchuk Avatar answered Oct 17 '22 21:10

Kirill Polishchuk


indexes in XPath are 1-based, not 0-based. Try

(//div[@class="post-content"]//img)[position()=2] 
like image 27
Colin Pickard Avatar answered Oct 17 '22 21:10

Colin Pickard