【问题标题】:Is it possible to make etree._Element printable?是否可以使 etree._Element 可打印?
【发布时间】:2021-08-26 10:05:59
【问题描述】:

在使用 lxml 时,我经常需要有关元素的更多信息。当使用print (element) 时,没有得到太多信息。有可能改变这个吗?如果我可以编写一个显示更多信息的自定义函数会很好,例如元素的文本。我已经尝试过setattr,但这不起作用。原因解释here.

一个例子:

from lxml import etree

root = etree.fromstring("<html>this is a test</html>")

print (root)

结果是:&lt;Element html at 0x7f582daeb700&gt;

更新:理想情况下,我希望能够只写print (element) 并获得格式良好的输出。我希望我能以某种方式使用custom __str__ 方法来实现这一点。

【问题讨论】:

  • 您是否尝试过etree.tostring(),可能带有pretty_print = True 参数?
  • 我的目标是仅使用 print(element) 来实现这一点,例如通过添加 str 方法。在该方法中,我确实可以添加 etree.tostring() 。 (相应地更新了问题以使这一点更清楚)
  • 可以继承etree,当然,但在我看来,这比仅仅使用print(element.tostring())复杂得多
  • 子类化可能无济于事,因为 etree 函数仍将返回“正常”etree-Elements。我想我正在寻找的东西根本不可能。

标签: python elementtree


【解决方案1】:

可以通过print(root.text)获取元素文本

【讨论】:

  • 感谢您的回答!我希望只使用 print(element) 没有外部函数,所以这对我不起作用。我相应地更新了问题。
【解决方案2】:

你可以在没有任何外部库的情况下做到这一点。就像下面这样:

import xml.etree.ElementTree as ET

root = ET.fromstring("<html>this is a test</html>")
ET.dump(root)

输出

<html>this is a test</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多