【问题标题】:lxml removes unwrapped text inside taglxml 删除标签内未包装的文本
【发布时间】:2016-07-29 14:16:52
【问题描述】:

这是我的带有 lxml 的 python 代码

import urllib.request
from lxml import etree
#import lxml.html as html
from copy import deepcopy
from lxml import etree
from lxml import html


some_xml_data = "<span>text1<div>ddd</div>text2<div>ddd</div>text3</span>"
root = etree.fromstring(some_xml_data)
[c] = root.xpath('//span')
print(etree.tostring(root))  #b'<span>text1<div>ddd</div>text2<div>ddd</div>text3</span>' #output as expected
#but if i do some changes
for e in c.iterchildren("*"):
    if e.tag == 'div':
        e.getparent().remove(e)

print(etree.tostring(root)) #b'<span>text1</span>' text2 and text3 removed! how to prevent this deletion?

看起来像在我对 lxml 树进行了一些更改之后(删除了一些标签) lxml 还删除了一些未包装的文本!如何防止 lxml 这样做并保存未包装的文本?

【问题讨论】:

    标签: python lxml


    【解决方案1】:

    节点之后的文本称为tail,可以通过附加到父节点的文本来保留,这里是一个示例:

    In [1]: from lxml import html
    
    In [2]: s = "<span>text1<div>ddd</div>text2<div>ddd</div>text3</span>"
       ...: 
    
    In [3]: tree = html.fromstring(s)
    
    In [4]: for node in tree.iterchildren("div"):
       ...:     if node.tail:
       ...:         node.getparent().text += node.tail
       ...:     node.getparent().remove(node)
       ...:     
    
    In [5]: html.tostring(tree)
    Out[5]: b'<span>text1text2text3</span>'
    

    我使用html,因为它比 xml 更可能是结构。您可以简单地使用iterchildrendiv 来避免额外检查标签。

    【讨论】:

      猜你喜欢
      • 2016-04-16
      • 2014-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多