寻找一种使用 Python urllib2 或任何其他 Python 库获取 HTTP 响应的字符集/编码信息的简单方法。
>>> url = 'http://some.url.value'
>>> request = urllib2.Request(url)
>>> conn = urllib2.urlopen(request)
>>> response_encoding = ?
我知道它有时会出现在“Content-Type” header 中,但该 header 还有其他信息,并且它嵌入在我需要解析的字符串中。例如,谷歌返回的 Content-Type header 是
>>> 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]
这种代码感觉工作量太大了。我也不确定它是否适用于所有情况。有没有人有更好的方法来做到这一点?
最佳答案
要解析 http header ,您可以使用 cgi.parse_header()
:
_, params = cgi.parse_header('text/html; charset=utf-8')
print params['charset'] # -> utf-8
或者使用响应对象:
response = urllib2.urlopen('http://example.com')
response_encoding = response.headers.getparam('charset')
# or in Python 3: response.headers.get_content_charset(default)
通常,服务器可能会谎报编码或根本不报告(默认取决于内容类型),或者可能在响应正文中指定编码,例如 <meta>
html 文档或 xml 文档的 xml 声明中的元素。作为最后的手段,可以从内容本身猜测编码。
您可以使用 requests
获取 Unicode 文本:
import requests # pip install requests
r = requests.get(url)
unicode_str = r.text # may use `chardet` to auto-detect encoding
或 BeautifulSoup
解析 html(并转换为 Unicode 作为副作用):
from bs4 import BeautifulSoup # pip install beautifulsoup4
soup = BeautifulSoup(urllib2.urlopen(url)) # may use `cchardet` for speed
# ...
或 bs4.UnicodeDammit
directly对于任意内容(不一定是 html):
from bs4 import UnicodeDammit
dammit = UnicodeDammit(b"Sacr\xc3\xa9 bleu!")
print(dammit.unicode_markup)
# -> Sacré bleu!
print(dammit.original_encoding)
# -> utf-8
关于python - 在 Python 中获取 HTTP 响应的字符集/编码的好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14592762/