从 lxml 中选择属性值
- 作者: 你的乳房滑过我的钢枪
- 来源: 51数据库
- 2023-01-06
问题描述
我想使用 xpath 表达式来获取属性的值.
I want to use an xpath expression to get the value of an attribute.
我希望以下工作
from lxml import etree
for customer in etree.parse('file.xml').getroot().findall('BOB'):
print customer.find('./@NAME')
但这给出了一个错误:
Traceback (most recent call last):
File "bob.py", line 22, in <module>
print customer.find('./@ID')
File "lxml.etree.pyx", line 1409, in lxml.etree._Element.find (src/lxml/lxml.etree.c:39972)
File "/usr/local/lib/python2.7/dist-packages/lxml/_elementpath.py", line 272, in find
it = iterfind(elem, path, namespaces)
File "/usr/local/lib/python2.7/dist-packages/lxml/_elementpath.py", line 262, in iterfind
selector = _build_path_iterator(path, namespaces)
File "/usr/local/lib/python2.7/dist-packages/lxml/_elementpath.py", line 246, in _build_path_iterator
selector.append(ops[token[0]](_next, token))
KeyError: '@'
我期望这会起作用吗?
推荐答案
find 和 findall 只实现 XPath 的一个子集.它们的存在是为了提供与其他 ElementTree 实现(如 ElementTree 和 cElementTree)的兼容性.
find and findall only implement a subset of XPath. Their presence is meant to provide compatibility with other ElementTree implementations (like ElementTree and cElementTree).
相比之下,xpath 方法提供对 XPath 1.0 的完全访问:
The xpath method, in contrast, provides full access to XPath 1.0:
print customer.xpath('./@NAME')[0]
但是,您可以改为使用 get:
However, you could instead use get:
print customer.get('NAME')
或属性:
print customer.attrib['NAME']
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
