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

看板Python作者 (yshihyu)時間8年前 (2016/10/23 00:14), 編輯推噓0(006)
留言6則, 1人參與, 最新討論串2/2 (看更多)
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 卻能正常輸出內容在終端機上? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 175.180.117.142 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1477152861.A.CD6.html

10/23 00:39, , 1F
一般不用改程式碼,若你用 linux 這 unix-based 系統
10/23 00:39, 1F

10/23 00:39, , 2F
用 bash 的話執行前 export PYTHONIOENCODING=utf-8
10/23 00:39, 2F

10/23 00:39, , 3F
執行一下設定環境變數就可以了
10/23 00:39, 3F

10/23 00:48, , 4F
至於那段語法可以解決主要是python2預設使用ascii編碼
10/23 00:48, 4F

10/23 00:49, , 5F
透過那語法後會讓內部處理都轉換指定為utf8
10/23 00:49, 5F

10/23 00:50, , 6F
python3 後續預設是走 unicode, 所以那段程式碼將無法用
10/23 00:50, 6F
文章代碼(AID): #1O2v1TpM (Python)
文章代碼(AID): #1O2v1TpM (Python)