2011-11-01 40 views
2

我想从下面的代码中的地址读取一些utf-8文件。它适用于其中的大部分,但对于某些文件,urllib2(和urllib)无法读取。来自urlopen的垃圾

这里很明显的答案是第二个文件已损坏,但奇怪的是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: 

回答

-1

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

2
>>> 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编码响应,或先解码。

+0

啊......我明白了。非常感谢! – user1023380