尝试处理一个非常简单的html5脚本并使用html5lib
进行渲染import html5lib
html = '''<!DOCTYPE html>
<html lang="en">
<head>
<title>Hi</title>
</head>
<body>
<script src="a.js"></script>
<script src="b.js"></script>
</body>
</html>
'''
parser = html5lib.HTMLParser(tree = html5lib.treebuilders.getTreeBuilder("lxml"))
walker = html5lib.treewalkers.getTreeWalker("lxml")
serializer = html5lib.serializer.htmlserializer.HTMLSerializer()
document = parser.parse(html)
stream = walker(document)
theHTML = serializer.render(stream)
print theHTML
输出如下:
<!DOCTYPE html><html lang=en><head>
<title>Hi</title>
</head>
<body>
<script src=a.js></script>
<script src=b.js></script>
烨。它只是切断了中途。将树构建器从lxml更改为dom不会执行任何操作。调整HTML会改变输出,但它仍然很糟糕。
答案 0 :(得分:1)
所以关键似乎是omit_optional_tags=False
以某种方式缺少它会输出结束。
parser = html5lib.HTMLParser(tree = html5lib.treebuilders.getTreeBuilder("lxml"))
document = parser.parse(html)
walker = html5lib.treewalkers.getTreeWalker("lxml")
stream = walker(document)
s = serializer.htmlserializer.HTMLSerializer(omit_optional_tags=False)
output_generator = s.serialize(stream)
for item in output_generator:
print item
<!DOCTYPE html>
<html lang=en>
<head>
<title>
Hi
</title>
</head>
<body>
<script src=a.js>
</script>
<script src=b.js>
</script>
</body>
</html>
>>>