我如何获得使用ElementTree的一个元素的全部文本? [英] How do I get the whole text of an element using ElementTree?

查看:177
本文介绍了我如何获得使用ElementTree的一个元素的全部文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也就是说,所有文字和子标签,没有一个元素本身的标签?

 < P>等等< B>的Bleh< / B> blih&所述; / P>

我想

 等等< B>的Bleh< / B> blih

element.text返回嗒嗒和etree.tostring(元素)返回:

 < P>等等< B>的Bleh< / B> blih&所述; / P>


解决方案

这是我结束了使用的解决方案:

 高清element_to_string(元):
    S = element.text或
    在元素sub_element:
        S + = etree.tostring(sub_element)
    S + = element.tail
    返回小号

That is, all text and subtags, without the tag of an element itself?

Having

<p>blah <b>bleh</b> blih</p>

I want

blah <b>bleh</b> blih

element.text returns "blah " and etree.tostring(element) returns:

<p>blah <b>bleh</b> blih</p>

解决方案

This is the solution I ended up using:

def element_to_string(element):
    s = element.text or ""
    for sub_element in element:
        s += etree.tostring(sub_element)
    s += element.tail
    return s

这篇关于我如何获得使用ElementTree的一个元素的全部文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆