Skip to main content
 首页 » 编程设计

python之来自 urlopen 的乱码

2025年05月04日8webabcd

我正在尝试从下面代码中的地址读取一些 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'} 

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