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