python爬虫错误之 “UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xd3 in position 252”

今天是学习爬虫第一天,俗话说万事开头难。刚写的第一个程序就报错了
源代码如下:

import urllib.request

url = "https://fishc.com.cn/"
response = urllib.request.urlopen(url)
html = response.read().decode("utf-8")
print(html)

错误如下:
在这里插入图片描述

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd3 in position 252: invalid continuation byte

翻译过来就是:
"utf-8”编解码器无法解码位置252中的字节0xd3:无效的连续字节

这个是解码出现了问题
我们去要爬的网站看一下,看看他的编码方式是什么
输入网站域名 --> 点击F12键
/img-blog.csdnimg.cn/20210509150034586.png)

我们可以看到是gbk编码方式,至此问题原因就找到了
修改代码,成功解决耶耶耶!

import urllib.request

url = "https://fishc.com.cn/"
response = urllib.request.urlopen(url)
html = response.read().decode("gbk")
print(html)


版权声明:本文为s_alted原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。