相当于 lxml 中 Beautiful Soup 的 renderContents() 方法?

发布于 2024-08-16 21:37:33 字数 333 浏览 2 评论 0原文

lxml 中是否有与 Beautiful Soup 的 tag.renderContents() 方法等效的方法?

我尝试过使用 element.text,但这不会渲染子标签,以及 ''.join(etree.tostring(child) for child in element),但这不会渲染子文本。我能找到的最接近的是etree.tostring(element),但是它呈现了element的开始和结束标签,这是我不想要的。

是否还有另一种我忽略的方法(或实现此目的的替代方法)?

Is there an equivalent of Beautiful Soup's tag.renderContents() method in lxml?

I've tried using element.text, but that doesn't render child tags, as well as ''.join(etree.tostring(child) for child in element), but that doesn't render child text. The closest I've been able to find is etree.tostring(element), but that renders the opening and closing tags of element, which I do not want.

Is there another method I'm overlooking (or an alternative approach to accomplish this)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

廻憶裏菂餘溫 2024-08-23 21:37:33

你的最初想法基本上已经实现了。 element.text 为您提供元素的第一个文本子元素,列表理解为您提供其他所有内容。如果您将两个字符串连接在一起,您就会得到您正在寻找的内容:

>>> xmlstr = "<sec>header <p>para 0</p> text <p>para 1</p> footer</sec>"
>>> element = etree.fromstring(xmlstr)
>>>
>>> element.text + "".join(map (etree.tostring, element))
'header <p>para 0</p> text <p>para 1</p> footer'
>>>

Ari。

You're most of the way there with your original idea. element.text gives you the first text child of the element, and your list comprehension gives you everything else. If you concatenate the two strings together, you get what you're looking for:

>>> xmlstr = "<sec>header <p>para 0</p> text <p>para 1</p> footer</sec>"
>>> element = etree.fromstring(xmlstr)
>>>
>>> element.text + "".join(map (etree.tostring, element))
'header <p>para 0</p> text <p>para 1</p> footer'
>>>

Ari.

丑丑阿 2024-08-23 21:37:33

一种黑客解决方案:

from lxml import etree
def render_contents(element):
    """
    Surely there is a safe lxml built-in for this...
    """
    tagname = element.tag
    return re.sub('</%s>\s*

编辑

真的,没有比这更好的方法了吗?

% tagname, '', re.sub(r'^<%s(\s+\w+=".*?")*?>' % tagname, '', etree.tostring(element))).strip()

编辑

真的,没有比这更好的方法了吗?

One hackish solution:

from lxml import etree
def render_contents(element):
    """
    Surely there is a safe lxml built-in for this...
    """
    tagname = element.tag
    return re.sub('</%s>\s*

Edit

Really, there's no better method than this?

% tagname, '', re.sub(r'^<%s(\s+\w+=".*?")*?>' % tagname, '', etree.tostring(element))).strip()

Edit

Really, there's no better method than this?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文