【问题标题】:Python HTML dump unicode errorPython HTML转储unicode错误
【发布时间】:2014-02-17 16:22:01
【问题描述】:

我正在创建一个系统,其中所有 url、html、文本、链接等都以 unicode 格式存储。为此,我从网页中提取 html 并使用粘贴在此处的代码将其转换为 unicode。我试过的几个链接工作正常。其他人喜欢下面我的源代码中的链接会引发错误。我该如何解决这个问题?

import urllib2
from cookielib import CookieJar
cj = CookieJar()
url = 'http://www.economist.com/news/leaders/21596515-there-are-lessons-many-governments-one-countrys-100-years-decline-parable'
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11 Chrome/32.0.1700.77 Safari/537.36'), ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'), ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'), ('Accept-Encoding','gzip,deflate,sdch'), ('Connection', 'keep-alive')]
resp = opener.open(url, timeout=5)
raw_html = resp.read()
raw_html.decode('utf-8')

给出错误:

UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: invalid start byte

【问题讨论】:

  • 尝试更改/删除请求的编码'Accept-Encoding','gzip,deflate,sdch'。
  • 您将它们存储在哪种 Unicode 编码中?在您的情况下,问题似乎是 decode 需要 utf-8 但会得到其他东西。

标签: python unicode encoding urllib2 python-unicode


【解决方案1】:

返回数据用GZip压缩。

  1. 你可以尝试解压:

    try:
        raw_html = GzipFile(fileobj=StringIO(raw_html)).read()
    except:
        pass
    
  2. 或者,您可以发送标头Accept-Encoding: deflate(不带“gzip”)

    opener.addheaders = [('Accept-Encoding', 'deflate'), ]
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    相关资源
    最近更新 更多