parse any HTML to XML using html5lib

倾然丶 夕夏残阳落幕 提交于 2019-12-08 17:20:43

You can use method to set an Element to be self-closing or not, something like this:

from lxml import etree

tree = etree.Element('div', attrib={'attr':'val', 'U00022':''})
etree.tostring(tree)
'<div U00022="" attr="val"/>'

# parse as self-closing tag
etree.tostring(tree, method='xml')
'<div U00022="" attr="val"/>'
# parse as normal HTML
etree.tostring(tree, method='html')
'<div U00022="" attr="val"></div>'

Then just do whatever you want from it. When you're trying to write from the Element, you can also add method too:

tree = html5lib.parse('<div attr="val" U00022="">', treebuilder='lxml', namespaceHTMLElements=False)
tree.write('yourfilename', method='html')

Printout:

<html><head></head><body><div u00022="" attr="val"></div></body></html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!