2022年 11月 3日

Python爬虫中文乱码问题(爬虫乱码)

在输出内容时,出现如下图的情况:

解决爬虫中文乱码的步骤 网址编码为gbk

  1. 查看网页源代码的head部分的编码:
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">,发现网页编码为gbk类型
  2. 利用requests库的方法查看默认输出的编码类型
  1. import requests
  2. url = 'https://chengdu.chashebao.com/yanglao/19077.html'
  3. response = requests.get(url)
  4. print(response.encoding)

输出结果为编码ISO-8859-1,并不是原网页的编码类型。

    3. 利用requests库改变输出结果的编码

  1. import requests
  2. url = 'https://chengdu.chashebao.com/yanglao/19077.html'
  3. response = requests.get(url)
  4. response.encoding = 'gbk'
  5. print(response.encoding)

输出结果为编码gbk,与原网页保持一致。

基于以上三个步骤,即可解决爬虫中文乱码问题。

代码

  1. import requests
  2. def get_html(url):
  3. try:
  4. response = requests.get(url)
  5. response.encoding = 'gbk' # 改变编码
  6. print(response.encoding)
  7. html = response.text
  8. return html
  9. except:
  10. print('请求网址出错')
  11. url = 'https://chengdu.chashebao.com/yanglao/19077.html'
  12. html = get_html(url)
  13. print(html)

效果展示如下图所示:

解决爬虫中文乱码的步骤 网址编码为utf-8

对于有些网页编码为utf-8的网址,输出事发现中文为乱码,此时我们需要进行两次重编码。

  1. response = requests.get(url, headers=headers)
  2. response.encoding = 'GBK'
  3. response.encoding = 'utf-8'

解决爬虫中文乱码的步骤 网址编码为gb2312

response.encoding = 'GBK'