【问题标题】:Partial loss of elements' text content using lxml使用 lxml 部分丢失元素的文本内容
【发布时间】:2017-09-11 05:10:37
【问题描述】:

我有一些 HTML 标记,我想在其中删除 <b> 元素的一些 <b> 子元素(它是旧标记...)。

问题:当我使用 Pythonlxml 删除子元素时,一些包含 <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>

如您所见,&lt;b&gt; 子元素消失了,但单词 NEVER 消失了,而 &lt;a&gt; 元素和文本 before the holiday! 保留了下来.

我不知道如何保留它!

【问题讨论】:

  • 您要删除粗体元素还是只删除粗体标签?
  • @James:元素和它们包含的所有内容,即整个节点 - 这确实按我的预期工作。

标签: python html python-3.x lxml


【解决方案1】:

尝试在要消除的元素上使用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>

【讨论】:

  • 太棒了!显然,“NEVER”是前一个节点&lt;b&gt; 的尾部文本,因此与之相关联。这有点不直观,因为它在技术上不在此元素内。
  • 没问题。请记得标记为已回答:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-27
  • 1970-01-01
  • 1970-01-01
  • 2015-11-16
  • 2015-03-16
  • 2020-05-12
相关资源
最近更新 更多