英文:
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 = '''<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)
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()='aaa']
是一个完全有效的XPath表达式。
对于你的XML,如果你被困在使用ElementTree
的情况下,可以尝试测试字符串值,.//p[.='aaa']
,这将是一个解决方法。更好的方法是只使用一个如lxml
这样更符合标准的XPath库。
另请参阅
英文:
.//p[text()='aaa']
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[.='aaa']
, 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论