在對html response的decode時拋出,代碼原樣為:
response = urllib.urlopen(dsturl) content = response.read().decode('utf-8')
拋出錯誤為
File "./unxingCrawler_p3.py", line 50, in getNewPhones content = response.read().decode() UnicodeDecodeError: 'utf8' codec can't decode byte 0xb2 in position 24137: invalid start byte
can't decode byte 0xb2 in position 24137
意思是聲明為utf-8編碼的網頁中出現了utf-8無法解析的字符,即遇到了非法字符——尤其是在某些用C/C++編寫的程序中,全角空格往往有多種不同的實現方式,比如\xa3\xa0,或者\xa4\x57,這些字符,看起來都是全角空格,但它們並不是“合法”的全角空格(真正的全角空格是\xa1\xa1),因此在轉碼的過程中出現了異常。
這樣的問題很讓人頭疼,因為只要字符串中出現了一個非法字符,整篇文章就都無法轉碼。
解決辦法:
unicodestr = json.loads(html.decode("gbk", “ignore”))
因為decode的函數原型是decode([encoding], [errors='strict']),可以用第二個參數控制錯誤處理的策略,默認的參數就是strict,代表遇到非法字符時拋出異常;
如果設置為ignore,則會忽略非法字符;
如果設置為replace,則會用?取代非法字符;
如果設置為xmlcharrefreplace,則使用XML的字符引用。