Skip to main content
 首页 » 编程设计

python之如何使用 Pythons urllib2 下载分块数据

2025年05月04日14freeliver54

我正在尝试使用 Python 2 从服务器下载一个大文件:

req = urllib2.Request("https://myserver/mylargefile.gz") 
rsp = urllib2.urlopen(req) 
data = rsp.read() 

服务器使用“Transfer-Encoding: chunked”发送数据,我只得到一些二进制数据,无法用 gunzip 解压。

我是否必须遍历多个 read()?还是多次请求?如果是这样,它们必须看起来像什么?

注意:我正在尝试仅使用 Python 2 标准库解决问题,而不使用其他库,例如 urllib3 或 requests。这可能吗?

请您参考如下方法:

来自 urllib2.urlopen 的 python 文档:

One caveat: the read() method, if the size argument is omitted or negative, may not read until the end of the data stream; there is no good way to determine that the entire stream from a socket has been read in the general case.

所以,循环读取数据:

req = urllib2.Request("https://myserver/mylargefile.gz") 
rsp = urllib2.urlopen(req) 
data = rsp.read(8192) 
while data: 
   # .. Do Something .. 
   data = rsp.read(8192)