寻找一种使用 Python urllib2 或任何其他 Python 库获取 HTTP 响应的字符集/编码信息的简单方法。
>>> url = 'http://some.url.value'
>>> request = urllib2.Request(url)
>>> conn = urllib2.urlopen(request)
>>> response_encoding = ?
我知道它有时会出现在“Content-Type”标头中,但该标头还有其他信息,并且它嵌入在我需要解析的字符串中。例如,谷歌返回的 Content-Type 标头是
>>> conn.headers.getheader('content-type')
'text/html; charset=utf-8'
我可以使用它,但我不确定格式的一致性。我很确定 charset 可能完全丢失,所以我必须处理这种极端情况。某种字符串拆分操作以从中获取 'utf-8' 似乎必须是做这种事情的错误方法。
>>> content_type_header = conn.headers.getheader('content-type')
>>> if '=' in content_type_header:
>>> charset = content_type_header.split('=')[1]
那种感觉就像是在做太多工作的代码。我也不确定它是否适用于所有情况。有没有人有更好的方法来做到这一点?