課程
/后端開發(fā)
/Python
/Python開發(fā)簡單爬蟲
出現(xiàn)這樣的編碼問題應(yīng)該怎么辦? 'ascii' codec can't decode byte 0xef in position 3: ordinal not in range(128)
2016-06-28
源自:Python開發(fā)簡單爬蟲 7-3
正在回答
在開始加上代碼:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
即可解決~
不用謝,請叫我雷鋒?。?/p>
原因分析
在解決錯誤之前,首先要了解unicode和utf-8的區(qū)別。
unicode指的是萬國碼,是一種“字碼表”。而utf-8是這種字碼表儲存的編碼方法。unicode不一定要由utf-8這種方式編成bytecode儲存,也可以使用utf-16,utf-7等其他方式。目前大多都以utf-8的方式來變成bytecode。
其次,python中字符串類型分為byte string 和 unicode string兩種。
如果在python文件中指定編碼方式為utf-8(#coding=utf-8),那么所有帶中文的字符串都會被認為是utf-8編碼的byte string(例如:mystr="你好"),但是在函數(shù)中所產(chǎn)生的字符串則被認為是unicode string
問題就出在這邊,unicode string 和 byte string 是不可以混合使用的,一旦混合使用了,就會產(chǎn)生這樣的錯誤。例如:
self.response.out.write("你好"+self.request.get("argu"))
其中,"你好"被認為是byte string,而self.request.get("argu")的返回值被認為是unicode string。由于預設(shè)的解碼器是ascii,所以就不能識別中文byte string。然后就報錯了。
以下有兩個解決方法
1.將字符串全都轉(zhuǎn)成byte string。
self.response.out.write("你好"+self.request.get("argu").encode("utf-8"))
2.將字符串全都轉(zhuǎn)成unicode string。
self.response.out.write(u"你好"+self.request.get("argu"))
byte string轉(zhuǎn)換成unicode string可以這樣轉(zhuǎn)unicode(unicodestring, "utf-8")
舉報
本教程帶您解開python爬蟲這門神奇技術(shù)的面紗
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網(wǎng)安備11010802030151號
購課補貼聯(lián)系客服咨詢優(yōu)惠詳情
慕課網(wǎng)APP您的移動學習伙伴
掃描二維碼關(guān)注慕課網(wǎng)微信公眾號
2016-08-10
在開始加上代碼:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
即可解決~
不用謝,請叫我雷鋒?。?/p>
2016-07-02
原因分析
在解決錯誤之前,首先要了解unicode和utf-8的區(qū)別。
unicode指的是萬國碼,是一種“字碼表”。而utf-8是這種字碼表儲存的編碼方法。unicode不一定要由utf-8這種方式編成bytecode儲存,也可以使用utf-16,utf-7等其他方式。目前大多都以utf-8的方式來變成bytecode。
其次,python中字符串類型分為byte string 和 unicode string兩種。
如果在python文件中指定編碼方式為utf-8(#coding=utf-8),那么所有帶中文的字符串都會被認為是utf-8編碼的byte string(例如:mystr="你好"),但是在函數(shù)中所產(chǎn)生的字符串則被認為是unicode string
問題就出在這邊,unicode string 和 byte string 是不可以混合使用的,一旦混合使用了,就會產(chǎn)生這樣的錯誤。例如:
self.response.out.write("你好"+self.request.get("argu"))
其中,"你好"被認為是byte string,而self.request.get("argu")的返回值被認為是unicode string。由于預設(shè)的解碼器是ascii,所以就不能識別中文byte string。然后就報錯了。
以下有兩個解決方法
1.將字符串全都轉(zhuǎn)成byte string。
self.response.out.write("你好"+self.request.get("argu").encode("utf-8"))
2.將字符串全都轉(zhuǎn)成unicode string。
self.response.out.write(u"你好"+self.request.get("argu"))
byte string轉(zhuǎn)換成unicode string可以這樣轉(zhuǎn)unicode(unicodestring, "utf-8")