这个html5lib脚本发生了什么?

时间:2012-02-02 05:35:30

标签: python html5lib

尝试处理一个非常简单的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会改变输出,但它仍然很糟糕。

1 个答案:

答案 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>
>>>