2012-04-05 40 views
10

获得元素我有下面的XPath表达式的XPath通过指数

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

运行在HTML页面上,扫描图像。 上面的查询返回很多图像,但我只想要列表中的第二个。

我已经试过

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

没有运气

我该怎么办呢?

感谢

回答

25

在XPath指数从1个位置开始,因此

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

应能正常工作,如果你要选择div[@class="post-content"]每个第二img。如果你必须选择从处于div[@class="post-content"]所有图像仅第二img,使用方法:在XPath的

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

优秀。虽然我不清楚,但你打了它。第二个是我正在寻找的。非常感谢 – Thomas 2012-04-05 08:51:33

+0

@Thomas,欢迎。 – 2012-04-05 08:53:59

6

指数是基于1,而不是0为主。尝试

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

这也适用 – Thomas 2012-04-05 08:52:11

+2

当然,XPath索引是基于1的......究竟是什么XPath? – 2015-10-07 15:35:38

+0

@JoeHakooz,http://mukulgandhi.blogspot.co.nz/2008/05/blog-post.html – 2016-08-30 22:09:29