【发布时间】: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 这样做并保存未包装的文本?
【问题讨论】: