元素树中具有属性的 xpath 表达式 python

xpath expression with attribute in Element tree python

import xml.etree.ElementTree as ET
tree: ET = ET.parse(file)
tree.find('.//ns1:tag/@someattribute', ns) 

导致{KeyError}'@',据我所知,xpath表达式是正确的,元素树中有没有办法直接使用xpath而不是直接获取属性值使用 .attrib

XPath 表达式在语法上是正确的。问题是 find() 只定位元素。它不能用于查找属性。

这应该有效:

attr = tree.find('.//ns1:tag', ns).get('someattribute')

对于 lxml,您可以使用 xpath() 方法(returns 一个列表):

attr = tree.xpath('.//ns1:tag/@someattribute', namespaces=ns)[0]