php xpath 按索引获取元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10025221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
xpath get element by index
提问by Thomas
I have the below xpath expression
我有以下 xpath 表达式
//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.
它在 html 页面上运行,扫描图像。上面的查询返回了很多图像,但我只想要列表中的第二个。
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
谢谢
回答by Kirill Polishchuk
In XPath index starts from 1 position, therefore
在 XPath 中索引从 1 个位置开始,因此
//div[@class="post-content"]//img[2]
should work correctly if you have to select each 2nd imgin div[@class="post-content"]. If you have to select only 2nd imgfrom all images that are in div[@class="post-content"], use:
如果您必须img在div[@class="post-content"]. 如果您只需img要从 中的所有图像中选择第二个div[@class="post-content"],请使用:
(//div[@class="post-content"]//img)[2]
回答by Colin Pickard
indexes in XPath are 1-based, not 0-based. Try
XPath 中的索引是基于 1 的,而不是基于 0 的。尝试
(//div[@class="post-content"]//img)[position()=2]

