我感到有點驚訝,它是如此複雜,以獲得與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)`的「字符集」參數與某些媒體類型一起使用來定義數據的字符集(3.4節)。當發件人未提供明確的字符集參數時,「文本」類型的媒體子類型在通過HTTP接收時定義爲具有默認字符集值「ISO-8859-1」。「作爲默認的旁註是ASCII。 – plundra 2010-12-22 15:05:21
@plundra:嗯,ISO-8859-1是ASCII的超集,但你是對的 - 它是一種不同的編碼。 – Piskvor 2010-12-22 15:07:10
@Piskvor:如果有人使用s上面的charset。解碼()例如,事情將中斷(與頁面發送ISO-8859-1,並依靠隱式) – plundra 2010-12-22 15:11:21