Python爬虫中文乱码问题

本文介绍了如何处理Python爬虫在抓取GBK和UTF-8编码网页时出现的中文乱码问题。首先,通过查看网页源代码确定编码类型,如GBK或UTF-8。然后,使用requests库获取网页内容时,根据网页实际编码设置response对象的encoding属性。对于GBK编码的网页,直接设置response.encoding为'gbk';而对于UTF-8编码的网页,可能需要进行两次重编码,先设置为GBK再转为UTF-8。通过这些步骤,可以有效解决爬虫中文乱码,确保正确显示网页内容。

我们在爬虫输出内容时,常常会遇到中文乱码情况(以如下网址为例)。

https://chengdu.chashebao.com/yanglao/19077.html

在输出内容时,出现如下图的情况:在这里插入图片描述

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

  1. 查看网页源代码的head部分的编码:
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">,发现网页编码为gbk类型
  2. 利用requests库的方法查看默认输出的编码类型
import requests

url = 'https://chengdu.chashebao.com/yanglao/19077.html'

response = requests.get(url)
print(response.encoding)  

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

  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网络爬虫过程中,遇到汉字乱码问题是比较常见的情况。根据引用\[1\]中提到的方法,我可以给你提供一些解决乱码问题的方法。 首先,你可以尝试使用引用\[2\]中的方法,即对于编码为utf-8的网址,进行两次重编码。你可以使用requests库发送请求,并在获取到的响应中设置编码为'GBK',然后再将编码设置为'utf-8'。这样可以解决一些网页中文乱码问题。 另外,你还可以尝试使用其他的编码方式来解决乱码问题。比如,可以尝试将编码设置为'gb2312',如引用\[2\]中提到的方法。这种方法适用于网址编码为'gb2312'的情况。 综上所述,解决Python爬虫中文乱码问题的步骤可以总结为: 1. 使用requests库发送请求获取网页内容。 2. 根据网页编码设置响应的编码方式,可以尝试设置为'GBK'或'gb2312'。 3. 如果仍然存在乱码问题,可以尝试进行多次编码转换,如将编码设置为'utf-8'。 希望以上方法能够帮助你解决Python爬虫中文乱码问题。如果还有其他问题,请随时提问。 #### 引用[.reference_title] - *1* [盘点3种Python网络爬虫过程中的中文乱码的处理方法](https://blog.csdn.net/i54996/article/details/120749614)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Python爬虫中文乱码问题](https://blog.csdn.net/wvqusrtg/article/details/113742520)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值