>> tree =-6ren">
gpt4 book ai didi

python - 无法在 objectify.parse 结果上调用 lxml.etree._ElementTree.find()

转载 作者:行者123 更新时间:2023-11-28 19:27:12 24 4
gpt4 key购买 nike

>>> from lxml import objectify
>>> from StringIO import StringIO
>>> f = StringIO("<root>data</root>")
>>> tree = objectify.parse(f)
>>> type(tree)
<type 'lxml.etree._ElementTree'>
>>> tree.find('root')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lxml.etree.pyx", line 1944, in lxml.etree._ElementTree.find (src/lxml/lxml.etree.c:45105)
TypeError: find() takes exactly one argument (2 given)
>>> tree.find()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lxml.etree.pyx", line 1926, in lxml.etree._ElementTree.find (src/lxml/lxml.etree.c:44970)
TypeError: find() takes at least 1 positional argument (0 given)
>>> print tree.find.__doc__
find(self, path, namespaces=None)

Finds the first toplevel element with given tag. Same as
``tree.getroot().find(path)``.

The optional ``namespaces`` argument accepts a
prefix-to-namespace mapping that allows the usage of XPath
prefixes in the path expression.

请注意 tree.getroot().find作品和find_ElementTree 上工作etree.parse 创建的实例.

主要问题:同一个方法如何引发这两个互斥的异常?另外,虽然我可以使用 tree.getroot().find ,如果它按记录工作,则更短的形式将是首选,所以我很好奇,这是一个 lxml 错误吗?

最佳答案

我们通过查看相应的来源(long live OSS)来解开这个谜团:

def find(self, path, namespaces=None):
u"""find(self, path, namespaces=None)

Finds the first toplevel element with given tag. Same as
``tree.getroot().find(path)``.

The optional ``namespaces`` argument accepts a
prefix-to-namespace mapping that allows the usage of XPath
prefixes in the path expression.
"""
self._assertHasRoot()
root = self.getroot()
if _isString(path):
start = path[:1]
if start == u"/":
path = u"." + path
elif start == b"/":
path = b"." + path
return root.find(path, namespaces)

"lxml.etree.pyx", line 1926 是片段的第一行,"lxml.etree.pyx", line 1944 是片段的最后一行,所以有实际上是两种不同的 find 方法。显然 objectify 构造了一些不接受 namespaces 参数的不同对象(因此这是 lxml 中的错误)。如果您使用 lxml.etree.parse 来解析您的 StringIO 对象,API 就可以正常工作。

关于python - 无法在 objectify.parse 结果上调用 lxml.etree._ElementTree.find(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7351188/

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