【发布时间】:2017-09-11 05:10:37
【问题描述】:
我有一些 HTML 标记,我想在其中删除 <b> 元素的一些 <b> 子元素(它是旧标记...)。
问题:当我使用 Python 和 lxml 删除子元素时,一些包含 <center> 元素的文本消失了。
示例程序(带有简化的说明性标记):
#!/usr/bin/env python3
from lxml import html, etree
from lxml.etree import tostring
html_snippet = """
<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>"""
tree = html.fromstring(html_snippet)
center_elem = tree.xpath("//center")[0]
print('----- BEFORE -----')
print(tostring(center_elem, pretty_print=True, encoding='unicode'))
for elem in center_elem.xpath("b"):
elem.getparent().remove(elem)
print('----- AFTER -----')
print(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>
<a href="#">change a running system</a> before the holidays!
</center>
如您所见,<b> 子元素消失了,但单词 NEVER 消失了,而 <a> 元素和文本 before the holiday! 保留了下来.
我不知道如何保留它!
【问题讨论】:
-
您要删除粗体元素还是只删除粗体标签?
-
@James:元素和它们包含的所有内容,即整个节点 - 这确实按我的预期工作。
标签: python html python-3.x lxml