我正在尝试从下面代码中的地址读取一些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:发布于 2011-11-01 18:09:43
>>> 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编码的响应,要么先对其进行解码。
发布于 2011-11-01 18:06:36
您请求的URL似乎引用了私有缓存。请尝试http://www.gutenberg.org/files/144/144-0.txt (可在http://www.gutenberg.org/ebooks/144找到)。
如果你真的想使用gzipped :服务器会向你发送/cache/格式的数据,而不是unicode。urllib2不要求gzipped压缩的数据,也不解码它,这是正确的行为。解压方法请参见this question。
发布于 2011-11-01 18:08:58
你知道这不是一个解决方案,但你应该看看urllib库,不管你是否还想使用http://pypi.python.org/pypi/requests可以查看请求的源代码,以了解它是如何与utf-8字符串一起工作的。
https://stackoverflow.com/questions/7964726
复制相似问题