python爬虫时,解决编码方式问题的万能钥匙(uicode,utf8,gbk......)

转载   原文:https://blog.csdn.net/xiongzaiabc/article/details/81008330 

无论遇到的网页代码是何种编码方式,都可以用以下方法统一解决

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') 进行编码回原来的编码方式
print html   

posted @ 2019-04-06 22:51  nevermore_29  阅读(231)  评论(0编辑  收藏  举报