gpt4 book ai didi

python - 我无法解决合法 XPATH 表达式上的 'lxml.etree.XPathEvalError: Invalid expression' 错误

转载 作者:行者123 更新时间:2023-12-01 08:09:24 25 4
gpt4 key购买 nike

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

应该工作的代码:

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

预期结果是一个 bool 值,但显示错误:

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

最佳答案

异常(exception)是因为 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

关于python - 我无法解决合法 XPATH 表达式上的 'lxml.etree.XPathEvalError: Invalid expression' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55354593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com