首页 > 编程语言 >python-爬虫-requests.get()-响应内容中文乱码

python-爬虫-requests.get()-响应内容中文乱码

时间:2022-10-28 14:34:25浏览次数:41  
标签:sys utf encoding python resp get 乱码 print


python-爬虫-requests.get()-响应内容中文乱码


由于目标url的headers没有提供charset,那么这串字节流就会用latin-1 转换为 unicode 编码的方式转换成了我们见到的unicode对象。
但是网页的编码方式实际上是utf-8,所以我们实际上需要的是从utf-8转换成unicode编码。 此时这一串字节流就会被错误地解释成unicode编码。
我们如何发现这种情况呢?
其实很简单,我们只要知道reponse的encoding方式是否错误就可以了,查看response对象的编码
resp = requests.get(’http://baidu.com‘) #请求
print '响应:\nencoding={}'.format(resp.encoding)  #如果中文乱码,如果requests没有发现http headers中的charset


如何转为 utf-8 输出?
我们可以在调用 txt = resp.text 之前设置 resp 对象的编码。resp.encoding='utf-8'


完整实例

# -*- coding: utf-8 -*-
import sys
import lxml
import requests
import codecs
import time
from lxml import etree,html
import tomd




reload(sys)
sys.setdefaultencoding('utf8') # 设置默认编码格式为'utf-8'


if sys.stdout.encoding != 'UTF-8':
sys.stdout = codecs.getwriter('utf-8')(sys.stdout, 'strict')
if sys.stderr.encoding != 'UTF-8':
sys.stderr = codecs.getwriter('utf-8')(sys.stderr, 'strict')




def http_get(url):
print '请求地址:{}'.format(url)
'''
'''
headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/58.0'}
resp = requests.get(url,headers=headers) #请求
print '请求完成'
if not resp:
print '无响应内容'
return
print '响应:\nencoding={}'.format(resp.encoding) #如果中文乱码,如果requests没有发现http headers中的charset
resp.encoding='gb2312' #设置响应编码(gbk、utf-8、gb2312)
txt = resp.text #获取响应的html内容
print '原始:\n{}'.format(txt)
print '响应:\nencoding={}'.format(resp.encoding)


http_get('http://baidu.com')




标签:sys,utf,encoding,python,resp,get,乱码,print
From: https://blog.51cto.com/u_4518216/5804857

相关文章