UnicodeEncodeError: ‘gbk‘ codec can‘t encode character ‘\u25aa‘ in position 11923: illegal multibyte

UnicodeEncodeError: ‘gbk’ codec can’t encode character ‘\u25aa’ in position 11923: illegal multibyte sequence之错误处理

一、问题简介

我在爬虫的时候出现了这个编码问题,但是我查看了网页的源代码,发现原网页就是UTF-8编码的,我搜索了好多好多的资料,还有很多实在CSDN上的,但是一直没有解决,而且我还在我的代码中进行了转码的工作:
(我的代码如下所示)

import requests
import re
import time
import warnings
# warnings.filterwarnings("ignore")
url = 'https://baike.baidu.com/item/Python/407313?fr=aladdin'
headers = {
    
    
    'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
        'AppleWebKit/537.36 (KHTML, like Gecko) '
        'Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.57'
}
response = requests.get(url=url, headers=headers)
response.encoding = 'utf-8'
print(response, '响应状态码是:', response.status_code)  # response.status_code是响应状态码
print('字符的编码为:', response.encoding)  # response.encoding 是返回网页的编码类型,比如:'gbk', 'utf-8', 'gb2312'等
# print(response.json())
# print(response.content)
# print(response.text)
print(response.text)

但一直都报这个错,无论我怎么转码都没有用:
在这里插入图片描述

二、问题的解决

随后我请教了我的Python老师,后来才明白了错误的原因:
网页的确是utf-8编码的,我的爬虫代码也没有问题,但是问题就是在于我的打印输出所选择的编码格式是GBK,所以应该将打印输出所选择的编码格式(是GBK), 也改为utf-8 ,这样就可以正常显示了:
完整解决过程如下:

1、打开这个界面:

在这里插入图片描述

2、接着再打开这个界面:

在这里插入图片描述

3、将上图中画红圈的编码改为UTF-8:

在这里插入图片描述
之后点击OK按钮即可

4、成功解决:

在这里插入图片描述
可以从上图中看出来,已经成功地显示出来了所需要的网页信息(即就是说:网页的源代码。)
由此,该问题就得到了成功的解决了~~~

以上就是我对我遇到的这个问题进行的解决,希望对大家有借鉴的意义。~~~

猜你喜欢

转载自blog.csdn.net/m0_54218263/article/details/115108277
今日推荐