I am not able to resolve 'lxml.etree.XPathEvalError: Invalid expression' error on a legal XPATH expression

I am not able to resolve 'lxml.etree.XPathEvalError: Invalid expression' error on a legal XPATH expression

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

应该工作的代码:

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

异常是因为 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.