Re: [問題] requests 撈回來的 big5 網頁轉成 utf8

作者: yshihyu (yshihyu)   2016-10-23 00:14:15
https://gist.github.com/anonymous/1078f4e653de5f1f9c6e98166b750212
加上 r.encoding = r.apparent_encoding 編碼確實就正常
python test.py 正常不會有亂碼
但我想我內容導向ruten.html會出現錯誤
python test.py > ruten.html
UnicodeEncodeError: 'ascii' codec can't encode characters in position
207-210: ordinal not in range(128)
錯誤 google 一下是解釋系統編碼是 ascii 編碼範圍只有0~127
但我加上下面兩行就可以成功導向 ruten.html
reload(sys)
sys.setdefaultencoding("utf-8")
好奇為什麼導向才會出現這問題? 而我程式裡面 print r.text 卻能正常輸出內容在終端機上?
謝謝
作者: kenduest (小州)   2016-10-23 00:39:00
一般不用改程式碼,若你用 linux 這 unix-based 系統用 bash 的話執行前 export PYTHONIOENCODING=utf-8執行一下設定環境變數就可以了至於那段語法可以解決主要是python2預設使用ascii編碼透過那語法後會讓內部處理都轉換指定為utf8python3 後續預設是走 unicode, 所以那段程式碼將無法用

Links booklink

Contact Us: admin [ a t ] ucptt.com