V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Exin
V2EX  ›  问与答

Python 抓取网页 html 乱码

  •  
  •   Exin · Apr 24, 2015 · 2346 views
    This topic created in 4033 days ago, the information mentioned may be changed or developed.
    通过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

    还请各位高手点拨一二。
    Supplement 1  ·  Apr 25, 2015
    今天用一样的代码突然跑通了
    3 replies    2015-04-25 16:04:39 +08:00
    fangjinmin
        1
    fangjinmin  
       Apr 24, 2015   ❤️ 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
       Apr 24, 2015
    @fangjinmin
    感谢!但我还是无法将该html的unicode正确编码并写入到文件。
    Exin
        3
    Exin  
    OP
       Apr 25, 2015
    已解决,部分页面内容是gzip的,而其他是普通的html
    通过chardet检测编码模式
    或者urllib2的request
    可以解决问题
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5047 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 03:57 · PVG 11:57 · LAX 20:57 · JFK 23:57
    ♥ Do have faith in what you're doing.