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

看板Python作者 (yshihyu)時間8年前 (2016/10/22 15:49), 8年前編輯推噓0(008)
留言8則, 2人參與, 最新討論串1/2 (看更多)
https://gist.github.com/anonymous/f7781da21b44925a36320e61b6f27283 print h.text # 亂碼 我範例是從露天拍賣抓資料可是出現都是亂碼, 後來google 有人提到露天網頁編碼是 big5 後來我找到有人針對露天拍賣編碼去轉成unicode http://bugcaptor.logdown.com/posts/181043-the-big5-page-requests-get-back-into-python-utf8 b = h.text.encode('latin-1').decode('big5') UnicodeDecodeError: 'big5' codec can't decode bytes in position 207-208: illegal multibyte sequence 但會出現上面錯誤訊息 後來我改成utf-8 網頁資料就正常 b = h.text.encode('latin-1').decode('utf-8') 好奇露天拍路編碼是 big5 那為什麼用 latin-1 轉成 str 在用decode('utf-8') 轉回 unicode 這樣會是正確? print h.encoding 想去看編碼可是看到編碼是 ISO-8859-1 怎麼跟big5 utf8 latin-1 都沒關係? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 175.180.117.245 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1477122558.A.2AF.html ※ 編輯: yshihyu (175.180.117.245), 10/22/2016 15:53:19

10/22 16:10, , 1F
看你讀取的網頁,本就是 UTF-8 編碼了
10/22 16:10, 1F

10/22 16:10, , 2F
直接使用 h.encoding = 'utf-8' 就可以了
10/22 16:10, 2F

10/22 16:16, , 3F
可以先手動用 h.apparent_encoding 猜測得到編碼,再固定轉碼
10/22 16:16, 3F

10/22 16:30, , 4F
至於 latin-1 轉 utf-8 可參考 #1NphJ8xb
10/22 16:30, 4F

10/22 16:40, , 5F
在網址前面加個 view-source: 就可以看到原始碼了
10/22 16:40, 5F

10/22 16:40, , 6F
你的網頁原始碼第四行就有聲明是utf-8囉
10/22 16:40, 6F

10/22 17:40, , 7F
補充一下,為何是 h.encoding 為 ISO-8859-1,可參考這篇
10/22 17:40, 7F
文章代碼(AID): #1O2nd-Al (Python)
文章代碼(AID): #1O2nd-Al (Python)