<span class='python'>
<a>google</a>
<a>chrome</a>
</span>
我想得到chrome
并让它像这样工作。
q = item.findall('.//span[@class="python"]//a')
t = q[1].text # first element = 0
我想把它合并成一个XPath表达式,只得到一个项而不是一个列表。
我试过了,但没有成功。
t = item.findtext('.//span[@class="python"]//a[2]') # first element = 1
而实际的,而不是简化的,HTML是这样的。
<span class='python'>
<span>
<span>
<img></img>
<a>google</a>
</span>
<a>chrome</a>
</span>
</span>
我不确定是什么问题。。。
这是关于
//
缩写的常见问题解答。.//a[2]
表示:选择当前节点的所有a
子节点,这些子节点是其父节点的第二个a
子节点。因此,这可能会选择多个元素或不选择元素——具体取决于具体的XML文档。简单地说,
[]
运算符的优先级高于//
。如果只希望返回所有节点中的一个(第二个),则必须使用方括号强制执行所需的优先级:
(.//a)[2]
这实际上选择了当前节点的第二个
a
后代。对于问题中使用的实际表达式,将其更改为:
或更改为:
来自评论:
你说得对。什么是
.//span[@class="python"]//a[2]
的意思?这将扩展到:它最终将选择第二个
a
子项(fn:position()
指的是child
轴)。因此,如果您的文档如下所示,则不会选择任何内容:如果需要所有子体中的第二个子体,请使用:
相关问题 更多 >
编程相关推荐