无论遇到的网页代码是何种编码方式,都可以用以下方法统一解决
import chardet
response = requests.get(url, headers=headers).content
cod = chardet.detect(response) #得到的结果格式类似为{'confidence': 0.99, 'encoding': 'GB2312'}
coding = cod['encoding'] #获取具体的编码方式
html = response.decode(coding, 'ignore') 进行编码回原来的编码方式
return html
注意:
str.decode(encoding='UTF-8',errors='strict')
- errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。