pythonlxml模块在内部使用哪种编码?

2024-06-28 20:01:02 发布

您现在位置:Python中文网/ 问答频道 /正文

当我得到一个网页时,我使用UnicodeDammit将其转换为utf-8编码,就像:

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)

但当我使用:

^{pr2}$

输出是<type 'lxml.etree._ElementUnicodeResult'>。 为什么?我以为是utf-8线。在


Tags: fromimporturl网页编码readhtmlcontent
2条回答

您可能希望跳过重新编码的步骤,因为lxml.html将自动使用源文件中指定的编码,而且只要它最终是有效的unicode,也许就没有理由关心它最初是如何编码的。在

除非你的项目是如此的小和非正式,你可以确保你永远不会遇到8位字符串(即,它总是7位ASCII,英语没有特殊字符),明智的做法是尽早将文本转换成unicode格式(比如在检索之后),并保持这种格式,直到您需要将其序列化以写入文件或通过套接字发送。在

您看到<type 'lxml.etree._ElementUnicodeResult'>的原因是lxml.html.fromstring()正在自动为您执行解码步骤。注意,这意味着上面的代码对于用UTF-16编码的页面不起作用,例如,因为8位字符串将用UTF-8编码,但html仍将显示UTF-16

<meta http-equiv="Content-Type" content="text/html; charset=utf-16" />

lxml将尝试根据utf-16编码规则对字符串进行解码,在短时间内引发一个异常。在

如果要将输出序列化为UTF-8编码的8位字符串,则只需:

^{pr2}$

lxml.etree._ElementUnicodeResult是继承自unicode的类:

$ pydoc lxml.etree._ElementUnicodeResult

lxml.etree._ElementUnicodeResult = class _ElementUnicodeResult(__builtin__.unicode)
 |  Method resolution order:
 |      _ElementUnicodeResult
 |      __builtin__.unicode
 |      __builtin__.basestring
 |      __builtin__.object

在Python中,有一些从基类型扩展来添加特定于模块的功能的类是相当常见的。应该像对待普通的Unicode对象一样安全。在

相关问题 更多 >