爬虫的编码问题
今天在做爬虫项目的时候,发现有报错。
代码如下:
response = urllib.request.urlopen(url)
html_b = response.read()
html = html_b.decode('utf-8')
错误:
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xbb in position 257: invalid start byte
意思是不能用utf-8转,然后想到可能是网页编码的问题
然后查看了下网页源码
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
于是就把代码改成如下
html = html_b.decode('gb2312')
错误:
UnicodeDecodeError: ‘gb2312’ codec can’t decode byte 0x9d in position 11496: illegal multibyte sequence
还是报错,然后查了好多资料才发现,应该用"gbk"。
总结
网页刚读取到的内容是二进制的,想要得到文字,就得转下编码。
具体转什么码要根据网页的编码来,一般是utf-8,但是像这次就是gbk。