作者yshihyu (yshihyu)
看板Python
标题[问题] requests 捞回来的 big5 网页转成 utf8
时间Sat Oct 22 15:49:10 2016
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://webptt.com/cn.aspx?n=bbs/Python/M.1477122558.A.2AF.html
※ 编辑: yshihyu (175.180.117.245), 10/22/2016 15:53:19
1F:→ zps: 看你读取的网页,本就是 UTF-8 编码了 10/22 16:10
2F:→ zps: 直接使用 h.encoding = 'utf-8' 就可以了 10/22 16:10
3F:→ zps: 可以先手动用 h.apparent_encoding 猜测得到编码,再固定转码 10/22 16:16
4F:→ zps: 至於 latin-1 转 utf-8 可参考 #1NphJ8xb 10/22 16:30
5F:→ Typebrook: 在网址前面加个 view-source: 就可以看到原始码了 10/22 16:40
6F:→ Typebrook: 你的网页原始码第四行就有声明是utf-8罗 10/22 16:40
7F:→ zps: 补充一下,为何是 h.encoding 为 ISO-8859-1,可参考这篇 10/22 17:40