我需要使用 lxml 下载和解析网页并构建 UTF-8 xml 输出。我认为伪代码中的模式更具说明性:
from lxml import etree
webfile = urllib2.urlopen(url)
root = etree.parse(webfile.read(), parser=etree.HTMLParser(recover=True))
txt = my_process_text(etree.tostring(root.xpath('/html/body'), encoding=utf8))
output = etree.Element("out")
output.text = txt
outputfile.write(etree.tostring(output, encoding=utf8))
所以 webfile 可以是任何编码(lxml 应该处理这个)。输出文件必须为 utf-8。我不确定在哪里使用编码/编码。这个架构好吗?(我找不到关于 lxml 和编码的好教程,但我可以找到很多问题......)我需要强大的解决方案。
编辑:
所以为了将 utf-8 发送到 lxml 我使用
converted = UnicodeDammit(webfile, isHTML=True)
if not converted.unicode:
print "ERR. UnicodeDammit failed to detect encoding, tried [%s]", \
', '.join(converted.triedEncodings)
continue
webfile = converted.unicode.encode('utf-8')