假设我有以下 xml:
<package xmlns="http://example/namespace">
<rating system="au-oflc">PG</rating>
...
</package>
要获取上面元素的文本,我正在执行以下操作:
from lxml import entree
f = open('/Users/David/Desktop/metadata.xml')
metadata_contents = f.read()
node = etree.fromstring(metadata_contents)
rating = node.xpath('//t:rating/text()', namespaces = {'t':'http://example/namespace'})
>>> rating
['PG']
我如何获得值“au-oflc”?
最佳答案
您需要检索节点本身,而不是它的文本:
rating = node.xpath('//t:rating', namespaces = {'t':'http://example/namespace'})
print rating[0].attrib['system']
关于python - 如何使用lxml查找元素属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9334762/