我们在爬虫输出内容时,常常会遇到中文乱码情况(以如下网址为例)。
https://chengdu.chashebao.com/yanglao/19077.html
在输出内容时,出现如下图的情况:
-
查看网页源代码的
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的网址,输出事发现中文为乱码,此时我们需要进行两次重编码。
response = requests.get(url, headers=headers)
response.encoding = 'GBK'
response.encoding = 'utf-8'
解决爬虫中文乱码的步骤 网址编码为gb2312
response.encoding = 'GBK'