我无法解决“ lxml.etree.XPathEvalError:无效的表达式”错误

时间:2019-03-26 10:14:48

标签: python python-3.x xpath lxml

我正在尝试解析xpath,但是它给出了无效的表达式错误。

应该执行的代码:

x = tree.xpath("//description/caution[1]/preceding-sibling::*/name()!='warning'")
print(x)

预期结果为布尔值,但显示错误。

  

回溯(最近通话最近):     在第9行的文件“ poc_xpath2.0_v1.py”       x = tree.xpath(“ //描述/警告[1] /上一个兄弟姐妹:: * / name()!='警告'”)     lxml.etree._ElementTree.xpath中的文件“ src \ lxml \ etree.pyx”,行2276     在lxml.etree.XPathDocumentEvaluator中,第359行的文件“ src \ lxml \ xpath.pxi”。调用     lxml.etree._XPathEvaluatorBase._handle_result中的文件“ src \ lxml \ xpath.pxi”,第227行   lxml.etree.XPathEvalError:表达式无效

1 个答案:

答案 0 :(得分:1)

异常是因为name()不是有效的节点类型。您的XPath仅在XPath 2.0或更高版本中有效。 lxml only supports XPath 1.0

您需要将name() != 'warning'移至predicate

此外,如果希望得到正确/错误的结果,请将xpath包裹在boolean() ...

tree.xpath("boolean(//description/caution[1]/preceding-sibling::*[name()!='warning'])")

完整示例...

from lxml import etree

xml = """
<doc>
    <description>
        <warning></warning>
        <caution></caution>
    </description>
</doc>"""

tree = etree.fromstring(xml)

x = tree.xpath("boolean(//description/caution[1]/preceding-sibling::*[name()!='warning'])")
print(x)

这将打印False

相关问题