爬取网站时,有的网站,进行“utf-8”解码时,报错。
注意:网站是utf-8编码没有错,不是gbk之类的其它编码。网站的实际编码可以通过浏览器的开发者工具(F12键)中的Console的浏览器控制平台输入如下代码,可以查看。
document.charset # 'UTF-8'
代码1:报错
from urllib.request import urlopen
res = urlopen('https://www.chinanews.com.cn/china/')
print(res.read().decode('utf-8')) # 报错
- 运行结果:是报错的
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 52988: invalid continuation byte
代码1的解决方法:decode(‘utf-8’,‘ignore’)
from urllib.request import urlopen
re