【问题标题】:I am not able to resolve 'lxml.etree.XPathEvalError: Invalid expression' error on a legal XPATH expression我无法解决合法 XPATH 表达式上的“lxml.etree.XPathEvalError: Invalid expression”错误
【发布时间】:2019-08-16 16:27:12
【问题描述】:

我正在尝试解析 xpath,但它给出了 Invalid expression 错误。

应该工作的代码:

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

预期结果是一个布尔值,但它显示错误:

Traceback (most recent call last):
  File "poc_xpath2.0_v1.py", line 9, in <module>
    x = tree.xpath("//description/caution[1]/preceding-sibling::*/name()!='warning'")
  File "src\lxml\etree.pyx", line 2276, in lxml.etree._ElementTree.xpath
  File "src\lxml\xpath.pxi", line 359, in lxml.etree.XPathDocumentEvaluator.__call__
  File "src\lxml\xpath.pxi", line 227, in lxml.etree._XPathEvaluatorBase._handle_result
lxml.etree.XPathEvalError: Invalid expression

【问题讨论】:

  • 首先,您使用的是什么版本的 xpath?其次,拥有您正在使用的 xml 代码会很有帮助。
  • 我的回答有帮助还是您还有问题?

标签: python python-3.x xpath lxml


【解决方案1】:

例外是因为name() 不是有效的节点类型。您的 XPath 只能作为 XPath 2.0 或更高版本有效。 lxml only supports XPath 1.0.

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

此外,如果您想要 True/False 结果,请将 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

【讨论】:

  • 谢谢丹尼尔。它工作得很好。再次感谢
猜你喜欢
  • 2020-05-11
  • 2015-06-23
  • 1970-01-01
  • 2019-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-25
相关资源
最近更新 更多