1. 程式人生 > >Python decode報錯UnicodeDecodeError: ‘gb2312’ codec can’t decode byte

Python decode報錯UnicodeDecodeError: ‘gb2312’ codec can’t decode byte

gb2312 遇到 字符 取代 使用 python 異常 報錯 設置

今天用python采集文章的時候發現有些中文會出現解碼出錯,UnicodeDecodeError: ‘gb2312’ codec can’t decode byte 0xb0 in position 18020: illegal multibyte sequence 百度了發現是繁體字之類的gb2312會出現錯誤,

直接用errors = ‘ignore‘忽略

html.decode("gb2312",errors = ‘ignore‘)

因為decode的函數原型是decode([encoding], [errors=‘strict‘]),可以用第二個參數控制錯誤處理的策略,默認的參數就是strict,代表遇到非法字符時拋出異常;

如果設置為ignore,則會忽略非法字符;
如果設置為replace,則會用?取代非法字符;
如果設置為xmlcharrefreplace,則使用XML的字符引用。

Python decode報錯UnicodeDecodeError: ‘gb2312’ codec can’t decode byte