26

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] 

3 Answers 3

60

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 want to select only 2nd img from all images that are in div[@class="post-content"], use:

(//div[@class="post-content"]//img)[2] 
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent. Though I was not clear, you hit it. The second one is what I was looking for. Thanks a lot
14

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

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

1 Comment

Of course XPath indexes are 1-based... what the hell XPath?
0

I have had this issue in the past the trick is understanding the index position.

so if you had a node like this

<div name="Something unique"> <div> ... <img/> </div> <div> ... <img/> </div> <img/> </div> <div> ... <img/> </div> <div> ... <img/> </div> </div> 

in this case the index goes after the first second node to indicate which node you need on the dom.

The valid xpath would be /div[@name="Something unique"]/div[3]//img

i hope this helps

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.