前言:
今天写爬虫的时候报了特殊编码的错,像b‘\xd8’(这个印象最深)
>>> '\xd8'
'Ø'
标题中的0用了Ø来表示,导致控制台报错,并且存入题目为空字符串。
解决办法如下:
import chardet
for index, font in enumerate(title):
try:
font_encoding = chardet.detect(font)['encoding']
except TypeError:
continue
else:
title[index] = font.decode(font_encoding)
detect函数会返回字节的编码类型,如果使用字符串类型会报TypeError的错
>>> chardet.detect(b'\xd8')
{'encoding': 'ISO-8859-1', 'confidence': 0.73, 'language': ''}
>>> chardet.detect('\xd8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\topsec\AppData\Roaming\Python\Python39\site-packages\chardet\__init__.py", line 36, in detect
raise TypeError('Expected object of type bytes or bytearray, got: '
TypeError: Expected object of type bytes or bytearray, got: <class 'str'>