V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Exin
V2EX  ›  问与答

Python 抓取网页 html 乱码

  •  
  •   Exin · 2015-04-24 11:45:22 +08:00 · 1975 次点击
    这是一个创建于 3328 天前的主题,其中的信息可能已经有所发展或是发生改变。
    通过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

    还请各位高手点拨一二。
    第 1 条附言  ·  2015-04-25 12:28:21 +08:00
    今天用一样的代码突然跑通了
    3 条回复    2015-04-25 16:04:39 +08:00
    fangjinmin
        1
    fangjinmin  
       2015-04-24 12:35:40 +08:00   ❤️ 1
    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
        2
    Exin  
    OP
       2015-04-24 13:53:25 +08:00
    @fangjinmin
    感谢!但我还是无法将该html的unicode正确编码并写入到文件。
    Exin
        3
    Exin  
    OP
       2015-04-25 16:04:39 +08:00
    已解决,部分页面内容是gzip的,而其他是普通的html
    通过chardet检测编码模式
    或者urllib2的request
    可以解决问题
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1444 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 987ms · UTC 17:26 · PVG 01:26 · LAX 10:26 · JFK 13:26
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.