不同网页可能使用的是不一样的网页编码,有的是gb2312,有的又可能是UTF-8.
当编码集使用错误,会出现乱码的情况
如何判断呢?
例如;这里是并发爬虫时做判断
async with session.get(self.url.format(page),headers=self.headers) as response:
当我们通过爬取内容后,得到response时,
content =await response.read()
content接收读取结果,然后得到其中的编码集类型
encoding = chardet.detect(content)['encoding']
再进行编码集的判断,当不是我们需要的编码集时,可以做不同处理
if encoding=='GB2312'or encoding=='ISO-8859-1':
result=content.decode('gbk')
else:
result = content.decode(encoding)
print('被反爬了...')