Python 元素部分丢失';使用lxml的文本内容

Python 元素部分丢失';使用lxml的文本内容,python,html,python-3.x,lxml,Python,Html,Python 3.x,Lxml,我有一些HTML标记,我想去掉元素的一些子元素(它是遗留标记…) 问题:当我使用Python和lxml删除子元素时,包含元素的部分文本消失 示例程序(带有简化的说明性标记): #/usr/bin/env蟒蛇3 从lxml导入html,etree 从lxml.etree导入到字符串 html_snippet=“” 这是智慧 请注意: 从来没有在假期之前! """ tree=html.fromstring(html\u代码段) center\u elem=tree.xpath(“//center”)

我有一些HTML标记,我想去掉
元素的一些
子元素(它是遗留标记…)

问题:当我使用Pythonlxml删除子元素时,包含
元素的部分文本消失

示例程序(带有简化的说明性标记):

#/usr/bin/env蟒蛇3
从lxml导入html,etree
从lxml.etree导入到字符串
html_snippet=“”
这是智慧
请注意:
从来没有在假期之前!
"""
tree=html.fromstring(html\u代码段)
center\u elem=tree.xpath(“//center”)[0]
打印('----在'---'之前)
打印(tostring(中间元素,pretty\u print=True,encoding='unicode'))
对于中间的元素_elem.xpath(“b”):
elem.getparent().remove(elem)
打印('----在'---'之后)
打印(tostring(中间元素,pretty\u print=True,encoding='unicode'))
输出:

----- BEFORE -----
<center>
    <b>IT wisdoms</b>
    <b>
        for your <a href="#">brain</a>:
    </b>
    NEVER <a href="#">change a running system</a> before the holidays!
</center>

----- AFTER -----
<center>
    <a href="#">change a running system</a> before the holidays!
</center>
----BEFORE-----
这是智慧
请注意:
从来没有在假期之前!
-----之后-----
在假期之前!
正如您所看到的,
孩子们不见了,但是单词永远不会消失,而
元素和文本在假期之前就消失了留下来

我不知道怎么保存它

尝试在要消除的元素上使用
drop_tree()

tree = html.fromstring(html_snippet)
center_elem = tree.xpath("//center")[0]
print('----- BEFORE -----')
print(etree.tostring(center_elem, pretty_print=True, encoding='unicode'))
for elem in center_elem.xpath("b"):
    elem.drop_tree()
print('----- AFTER -----')
print(etree.tostring(center_elem, pretty_print=True, encoding='unicode'))
返回:

----- BEFORE -----
<center>
    <b>IT wisdoms</b>
    <b>
        for your <a href="#">brain</a>:
    </b>
    NEVER <a href="#">change a running system</a> before the holidays!
</center>

----- AFTER -----
<center>


    NEVER <a href="#">change a running system</a> before the holidays!
</center>
----BEFORE-----
这是智慧
请注意:
从来没有在假期之前!
-----之后-----
从来没有在假期之前!

您想删除粗体元素还是只删除粗体标记?@James:元素和它们包含的所有内容,即整个节点-这确实像我预期的那样有效。太棒了!显然,“从不”是前面节点的尾部文本,因此与之关联。这有点不直观,因为技术上它不在这个元素中。没问题。请记住标记为回答:)
----- BEFORE -----
<center>
    <b>IT wisdoms</b>
    <b>
        for your <a href="#">brain</a>:
    </b>
    NEVER <a href="#">change a running system</a> before the holidays!
</center>

----- AFTER -----
<center>


    NEVER <a href="#">change a running system</a> before the holidays!
</center>