Python爬虫中文乱码问题

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

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'
  • 44
    点赞
  • 128
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值