使用lxml庫清理和規范化HTML文檔的步驟如下:
from lxml import etree
html = """
<html>
<head>
<title>Example</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is an example HTML document.</p>
</body>
</html>
"""
# 將HTML文檔轉換為lxml對象
tree = etree.HTML(html)
# 使用tostring方法將lxml對象轉換回字符串,清理HTML文檔
clean_html = etree.tostring(tree, pretty_print=True, method="html").decode('utf-8')
# 使用tostring方法的method參數規范化HTML文檔
normalized_html = etree.tostring(tree, pretty_print=True, method="xml").decode('utf-8')
通過以上步驟,您可以使用lxml庫清理和規范化HTML文檔。