xpath get element by index

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

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

with no luck

How can I do it?

thanks

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]

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

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

Need Your Help

Convert C# 2.0 System.Data.SqlTypes.SqlXml object into a System.Xml.XmlNode

c# sqldatareader sqlxml xmlnode

I seem to always have problems with converting data to and from XML in C#. It always wants you to create a full XMLDocument object even when you think you shouldn't have to. In this case I have a S...

Pop up while re-subscribing for product in sandbox environment

ios xcode in-app-purchase sandbox

I am creating app in which user have to subscribe for product for 1 month/year. I was testing app in sandbox environment. For that i created test user account from itunes connect. I purchase product