繁体   English   中英

来自urlopen的胡言乱语

[英]Gibberish from urlopen

我正在尝试从下面的代码中的地址中读取一些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:
>>> 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编码响应的标头,或者先对其进行解码。

您要求的URL似乎是指专用缓存。 请改用http://www.gutenberg.org/files/144/144-0.txt (位于http://www.gutenberg.org/ebooks/144 )。

如果您确实要使用/cache/ URL:服务器正在向您发送压缩数据,而不是unicode。 urllib2不会要求压缩数据,也不会对其进行解码,这是正确的行为。 这个问题对于如何解压。

您知道这不是解决方案,但您应该查看http://pypi.python.org/pypi/requests库,无论您是否仍要使用urllib,都可以查看Requests的源代码,以了解它如何与utf一起使用-8弦。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM