【问题标题】:Gibberish from urlopen来自 urlopen 的乱码
【发布时间】:2011-11-01 09:43:07
【问题描述】:

我正在尝试从以下代码中的地址读取一些 utf-8 文件。它适用于大多数文件,但对于某些文件,urllib2(和 urllib)无法读取。

这里的明显答案是第二个文件已损坏,但奇怪的是 IE 读取它们都没有问题。该代码已在 XP 和 Linux 上进行了测试,结果相同。有什么建议吗?

import urllib2
#This works:
f=urllib2.urlopen("http://www.gutenberg.org/cache/epub/145/pg145.txt")
line=f.readline()
print "this works: %s)" %(line)
line=unicode(line,'utf-8') #... works fine

#This doesn't
f=urllib2.urlopen("http://www.gutenberg.org/cache/epub/144/pg144.txt")
line=f.readline()
print "this doesn't: %s)" %(line)
line=unicode(line,'utf-8')#...causes an exception:

【问题讨论】:

    标签: python utf-8 urlopen


    【解决方案1】:
    >>> f=urllib2.urlopen("http://www.gutenberg.org/cache/epub/144/pg144.txt")
    >>> f.headers.dict
    {'content-length': '304513', ..., 'content-location': 'pg144.txt.utf8.gzip', 'content-encoding': 'gzip', ..., 'content-type': 'text/plain; charset=utf-8'}
    

    要么设置一个标头来阻止站点发送 gzip 编码的响应,要么先对其进行解码。

    【讨论】:

      【解决方案2】:

      您要求的 URL 似乎是指私人缓存。请改用http://www.gutenberg.org/files/144/144-0.txt(在http://www.gutenberg.org/ebooks/144 找到)。

      如果您真的想使用/cache/ URL:服务器正在向您发送 gzip 压缩数据,而不是 unicode。 urllib2 不要求 gzip 压缩的数据,也不对其进行解码,这是正确的行为。 解压方法见this question

      【讨论】:

        【解决方案3】:

        你知道这不是一个解决方案,但你应该看看http://pypi.python.org/pypi/requests library,不管你是否还想使用 urllib 可以看看 Requests 的源代码,了解它是如何与 utf-8 字符串一起工作的。

        【讨论】:

          猜你喜欢
          • 2017-10-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-09
          • 2023-03-07
          • 2013-11-18
          • 1970-01-01
          相关资源
          最近更新 更多