Python 抓取网页 html 乱码

2015-04-24 11:45:22 +08:00
 Exin
通过Chrome查看页面源代码,我有看到charset=utf-8,页面应是utf-8编码的。
系统是Windows8.1
通过python的urllib2的urlopen下载html,拿到本地的是乱码。
而Chrome另存为到本地则可以成功读取(另存为时格式也是utf-8)
已经尝试了encode+decode,gbk, gb2312似乎都不起效。

网页地址:
http://wiki.52poke.com/wiki/%E5%A6%99%E8%9B%99%E7%A7%8D%E5%AD%90

还请各位高手点拨一二。
1984 次点击
所在节点    问与答
3 条回复
fangjinmin
2015-04-24 12:35:40 +08:00
import urllib
import codecs
url = 'http://wiki.52poke.com/wiki/%E5%A6%99%E8%9B%99%E7%A7%8D%E5%AD%90'
response = urllib.urlopen(url)
charset = response.headers.getparam('charset')
html = response.read()

if charset != '':
try:
codecs.lookup(charset)
html = html.decode(charset, 'replace')
except:
pass
Exin
2015-04-24 13:53:25 +08:00
@fangjinmin
感谢!但我还是无法将该html的unicode正确编码并写入到文件。
Exin
2015-04-25 16:04:39 +08:00
已解决,部分页面内容是gzip的,而其他是普通的html
通过chardet检测编码模式
或者urllib2的request
可以解决问题

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/185969

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX