UnicodeDecodeError: 'utf-8' codec can't decode byte 报错。
原因:爬取的网站编码和decode默认的utf8编码不同,例如:gbk
解决办法:
1、忽略掉utf8编码
def parse(self, response): print(response.body.decode("utf8", "ignore")) return
但这样做的结果是网站中的代码都是乱码
2、从meta 中提取charset,然后根据charset类型写对应的解析编码方式
例如:一个网站的metah如下:
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
则代码可以先从meta中提取出charset,然后再解析,如下(这里只用content判断应该还不够,只能满足一般情况):
charset = re.findall('content="text/html; charset=(.*?)"', response.body.decode('utf8','ignore')) print(charset) if charset: print(response.body.decode(charset[0])) else: print(response.body.decode())