小编典典

在Python中获取HTTP响应的字符集/编码的好方法

python

寻找一种简单的方法来使用Python urllib2或任何其他Python库获取HTTP响应的字符集/编码信息。

>>> url = 'http://some.url.value'
>>> request = urllib2.Request(url)
>>> conn = urllib2.urlopen(request)
>>> response_encoding = ?

我知道有时它会出现在“ Content-Type”标头中,但是该标头还有其他信息,并且它嵌入了我需要解析的字符串中。例如,Google返回的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]

那种代码感觉像是在做太多的工作。我也不确定是否在每种情况下都可以使用。有谁有更好的方法来做到这一点?


阅读 324

收藏
2021-01-20

共1个答案

小编典典

要解析http标头,您可以使用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直接获取任意内容(不一定是html):

from bs4 import UnicodeDammit

dammit = UnicodeDammit(b"Sacr\xc3\xa9 bleu!")
print(dammit.unicode_markup)
# -> Sacré bleu!
print(dammit.original_encoding)
# -> utf-8
2021-01-20