从lxml中选择属性值

问题描述

| 我想使用xpath表达式来获取属性的值。 我期望以下工作
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,line 246,in _build_path_iterator
    selector.append(ops[token[0]](_next,token))
KeyError: \'@\'
我期望这个工作正常吗?     

解决方法

find
findall
仅实现XPath的子集。它们的存在是为了与其他ElementTree实现(例如
ElementTree
cElementTree
)兼容。 相比之下,
xpath
方法提供了对XPath 1.0的完全访问权限:
print customer.xpath(\'./@NAME\')[0]
但是,您可以改用
get
print customer.get(\'NAME\')
attrib
print customer.attrib[\'NAME\']
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...