我们在爬虫输出内容时,常常会遇到中文乱码情况(以如下网址为例)。
https://chengdu.chashebao.com/yanglao/19077.html
在输出内容时,出现如下图的情况:
解决爬虫中文乱码的步骤 网址编码为gbk
- 查看网页源代码的
head部分的编码:<meta http-equiv="Content-Type" content="text/html; charset=gb2312">,发现网页编码为gbk类型 - 利用
requests库的方法查看默认输出的编码类型
import requests
url = 'https://chengdu.chashebao.com/yanglao/19077.html'
response = requests.get(url)
print(response.encoding)
输出结果为编码ISO-8859-1,并不是原网页的编码类型。
- 利用
requests库改变输出结果的编码
import requests
url = 'https://chengdu.chashebao.com/yanglao/19077.html'
response = requests.get(url)
response.encoding = 'gbk'
print(response.encoding)
输出结果为编码gbk,与原网页保持一致。
基于以上三个步骤,即可解决爬虫中文乱码问题。
代码
import requests
def get_html(url):
try:
response = requests.get(url)
response.encoding = 'gbk' # 改变编码
print(response.encoding)
html = response.text
return html
except:
print('请求网址出错')
url = 'https://chengdu.chashebao.com/yanglao/19077.html'
html = get_html(url)
print(html)
效果展示如下图所示:
解决爬虫中文乱码的步骤 网址编码为utf-8
对于有些网页编码为utf-8的网址,输出事发现中文为乱码,此时我们需要进行两次重编码。
response = requests.get(url, headers=headers)
response.encoding = 'GBK'
response.encoding = 'utf-8'
解决爬虫中文乱码的步骤 网址编码为gb2312
response.encoding = 'GBK'
本文介绍了如何处理Python爬虫在抓取GBK和UTF-8编码网页时出现的中文乱码问题。首先,通过查看网页源代码确定编码类型,如GBK或UTF-8。然后,使用requests库获取网页内容时,根据网页实际编码设置response对象的encoding属性。对于GBK编码的网页,直接设置response.encoding为'gbk';而对于UTF-8编码的网页,可能需要进行两次重编码,先设置为GBK再转为UTF-8。通过这些步骤,可以有效解决爬虫中文乱码,确保正确显示网页内容。
1500

被折叠的 条评论
为什么被折叠?



