【发布时间】:2011-05-29 11:13:46
【问题描述】:
我有点惊讶,用 Python 获取网页的字符集是如此复杂。我错过了一条路吗? HTTPMessage 有很多函数,但没有这个。
>>> google = urllib2.urlopen('http://www.google.com/')
>>> google.headers.gettype()
'text/html'
>>> google.headers.getencoding()
'7bit'
>>> google.headers.getcharset()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: HTTPMessage instance has no attribute 'getcharset'
所以你必须得到标题,然后拆分它。两次。
>>> google = urllib2.urlopen('http://www.google.com/')
>>> charset = 'ISO-8859-1'
>>> contenttype = google.headers.getheader('Content-Type', '')
>>> if ';' in contenttype:
... charset = contenttype.split(';')[1].split('=')[1]
>>> charset
'ISO-8859-1'
对于这样一个基本功能,步骤数量惊人。我错过了什么吗?
【问题讨论】:
-
来自 RFC 2616 (HTTP1.1)
The "charset" parameter is used with some media types to define the character set (section 3.4) of the data. When no explicit charset parameter is provided by the sender, media subtypes of the "text" type are defined to have a default charset value of "ISO-8859-1" when received via HTTP.,作为默认为 ASCII 的旁注。 -
@plundra:嗯,ISO-8859-1 是 ASCII 的超集,但你是对的 - 它是不同的编码。
-
@Piskvor:例如,如果将上面的
charset与 s.decode() 一起使用,事情就会中断(页面发送 iso-8859-1 并依赖于隐式) -
啊,所以我应该检查类型,如果是文本,它应该默认为 latin-1,否则它可能是二进制的,根本不应该被解码。 :) 又是复杂的一步。
标签: python http content-type