python - dir(element) 返回不存在的元素。尝试使用 getattr(element, ...) 失败

标签 python lxml.objectify

基本上我做的是:

attrs = dir(oe)
for attr in attrs:
  attr_obj = getattr(oe, attr)

  .... more code ...

但是 getattr 调用失败并显示:AttributeError: no such child: comment

oelxml.objectify 库的一个 ObjectifiedElement

当我使用 PyCharm 查看 oe 时,它显示了 comment 属性,但也无法解析它。

这是怎么回事? dir 不存在时如何显示该属性?

最佳答案

我不是专家,但 lxml 可能会重新定义 __getattr__ 。从他们的源代码:

def __getattr__(self, tag):
    u"""Return the (first) child with the given tag name.  If no namespace
    is provided, the child will be looked up in the same one as self.
    """
    if is_special_method(tag):
        return object.__getattr__(self, tag)
    return _lookupChildOrRaise(self, tag)

参见 https://github.com/lxml/lxml/blob/master/src/lxml/lxml.objectify.pyx

此外,关于 dir 方法,您有:

目录([对象]) 没有参数,返回当前本地范围内的名称列表。使用参数,尝试返回该对象的有效属性列表。

如果对象有一个名为dir() 的方法,这个方法将被调用并且必须返回属性列表。这允许实现自定义 getattr() 或 getattribute() 函数的对象自定义 dir() 报告其属性的方式。

如果对象不提供 dir(),该函数会尽力从对象的 dict 属性(如果已定义)及其类型对象中收集信息。结果列表不一定完整,并且当对象具有自定义 getattr() 时可能不准确。

参见 https://docs.python.org/2/library/functions.html#dir

关于python - dir(element) 返回不存在的元素。尝试使用 getattr(element, ...) 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33363681/

相关文章:

python - 在Python中将屏幕输出发送到/dev/null

python - 超时后如何中止 multiprocessing.Pool 中的任务?

python - 当没有这样的命名列时,SQLite 给出找不到列的错误

Python:如何使用 lxml objectify 的 iterchildren 获取不同命名空间中 sibling 的详细信息

python - 从对象化 XML 中高效获取多个切片

python - Pandas 空数据帧由 isin 函数生成,如果 ID 存在于仅包含 ID 的数据帧中,则该函数会保留具有 ID 的对象

python - 通过添加列组来创建新列

python - 在 lxml objectify python 中将 int 元素更改为 str 元素

python - 如何获取 lxml.etree._ElementTree 对象的父路径

python - lxml.objectify.parse 失败而 fromstring 工作