使用lxml在python中编码 - 复杂的解决方案

Voj*_*lko 10 python lxml

我需要使用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))
Run Code Online (Sandbox Code Playgroud)

所以webfile可以是任何编码(lxml应该处理这个).Outputfile必须是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')
Run Code Online (Sandbox Code Playgroud)

Ian*_*ing 18

关于输入编码,lxml可能有点不稳定.最好发送UTF8并输出UTF8.

您可能希望使用chardet模块或UnicodeDammit来解码实际数据.

你想做一些模糊的事情:

import chardet
from lxml import html
content = urllib2.urlopen(url).read()
encoding = chardet.detect(content)['encoding']
if encoding != 'utf-8':
    content = content.decode(encoding, 'replace').encode('utf-8')
doc = html.fromstring(content, base_url=url)
Run Code Online (Sandbox Code Playgroud)

我不确定你为什么要在lxml和etree之间移动,除非你正在与另一个已经使用了etree的库进行交互?

  • 为什么不直接将解码后的字符串(unicode对象)传递给html.fromstring(),而不是将其重新编码为utf-8? (2认同)