python - python lxml 模块在内部使用哪种编码?

标签 python encoding lxml

当我得到一个网页时,我使用 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)

但是当我使用时:

text = doc.text_content()
print type(text)

输出是<type 'lxml.etree._ElementUnicodeResult'> . 为什么?我以为它会是一个 utf-8 字符串。

最佳答案

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 字符串应该是安全的。

关于python - python lxml 模块在内部使用哪种编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13983729/

相关文章:

python: UnicodeDecodeError: 'utf8' 编解码器无法解码位置 0 中的字节 0xc0:起始字节无效

java - 在 Java StAX 解析器中编码

mysql 字符集 utf 8 排序规则(dup 键)无法正常工作

python - 在 Python 中生成非常大的 XML 文件?

python - 如何使用Python下载文件并进行身份验证

python - 使用python代码将MySql列中的 "NAN"值转换为NULL

python - Intellij/Pycharm 无法调试 Python 模块

python - 使用 lxml.etree 移动整个元素

python - 为什么此解析器找不到使用 namespace 前缀的 XML 标记的内容?

python - Fedora 中用于 numpy/scipy/scikit-learn 的 python virtualenv 上的 ATLAS