XPath语法错误:使用text()的谓词无效。

huangapple go评论72阅读模式
英文:

XPath SyntaxError: invalid predicate with text()

问题

以下是翻译好的部分:

在Python中使用我认为是有效的XPath表达式时,我遇到了“SyntaxError: invalid predicate”错误。

我的代码是:

import xml.etree.ElementTree as ET
data = '''<root>
            <child>
                <p>aaa</p>
                <p>bbb</p>
            </child>
        </root>'''

root = ET.fromstring(data)

p_element = root.findall(".//p[text()='aaa']")

print(p_element[0].text)

运行这段代码会产生无效的谓词错误,但我认为它是正确的。我使用的是Python版本3.10.0,并在Windows上运行。

似乎与XPath中的text()部分有关;如果将其删除,就不会出现错误。

英文:

What am I doing wrong?

When using what I believe to be a valid XPath expression in Python, I get

> SyntaxError: invalid predicate

My code is:

import xml.etree.ElementTree as ET
data = &#39;&#39;&#39;&lt;root&gt;
            &lt;child&gt;
                &lt;p&gt;aaa&lt;/p&gt;
                &lt;p&gt;bbb&lt;/p&gt;
            &lt;/child&gt;
        &lt;/root&gt;&#39;&#39;&#39;

root = ET.fromstring(data)

p_element = root.findall(&quot;.//p[text()=&#39;aaa&#39;]&quot;)

print(p_element[0].text)

Running this code produces an invalid predicate error, but I believe it is correct. I'm using Python version 3.10.0, and running this on Windows.

It seems to have something to do with the text() part of the XPath; with that removed, it does not error.

答案1

得分: 2

.//p[text()=&#39;aaa&#39;] 是一个完全有效的XPath表达式。

问题在于ElementTree的XPath实现不完整

对于你的XML,如果你被困在使用ElementTree的情况下,可以尝试测试字符串值,.//p[.=&#39;aaa&#39;],这将是一个解决方法。更好的方法是只使用一个如lxml这样更符合标准的XPath库。

另请参阅

英文:

.//p[text()=&#39;aaa&#39;] is a perfectly valid XPath expression.

The problem is that ElementTree's implementation of XPath is incomplete.

For your XML, testing the string value, .//p[.=&#39;aaa&#39;], would be a work-around if you're stuck with ElementTree. Better would be to only use an XPath library such as lxml that better follows the standard.

See also

huangapple
  • 本文由 发表于 2023年5月11日 09:00:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76223475.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定