来自:https://blog.csdn.net/chaowanghn/article/details/54889835
分析:
在使用requests模块爬取数据时,爬取的网页经常容易出现乱码问题,如下:
对于:
res = requests.get(url)
res.text
返回的是Unicode型的数据,一般用于读取文本。res.content
返回的是bytes型的数据,一般用于读取文件、图片。
解决办法
1. 使用 res.content 转化为byte型,再转化为str型
# 方式1
res = requests.get(url=url, headers=headers).content
page_data = str(res, 'utf-8')
# 方式2
page_data = requests.get(url=url, headers=headers).content.decode('utf-8')
2. 使用 res.text
Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 r.text 之时,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用r.encoding
属性来改变它.
当Requests库的自身编码为: r.encoding = ‘ISO-8859-1’
可以 r.encoding 修改编码:
res = requests.get(url=url, headers=headers)
res.encoding = 'utf-8'
page_text = res.text
print(page_text)