如何防止lxml修改标记
from lxml import etree
from lxml.html.soupparser import fromstring
html = '<iframe width="560" height="315" src="" frameborder="0" allowfullscreen></iframe>'
root = fromstring(html)
print etree.tostring(root,encoding='utf-8')
它打印短版标签
'<iframe width="560" height="315" src="" frameborder="0" allowfullscreen/>'
如何预防?所需输出
'<iframe width="560" height="315" src="" frameborder="0" allowfullscreen></iframe>'
是吗?
最佳答案
将tostring()
与method="html"
一起使用:
print etree.tostring(root.find('iframe'), encoding='utf-8', method="html")
演示:
>>> from lxml import etree
>>> from lxml.html.soupparser import fromstring
>>>
>>> html = '<iframe width="560" height="315" src="" frameborder="0" allowfullscreen></iframe>'
>>> root = fromstring(html)
>>> print etree.tostring(root.find('iframe'), encoding='utf-8', method="html")
<iframe allowfullscreen="allowfullscreen" frameborder="0" height="315" src="" width="560"></iframe>