从URL下载返回的Zip文件

use*_*108 56 python url zip urllib download

如果我有一个URL,当在Web浏览器中提交时,弹出一个对话框来保存zip文件,我将如何在Python中捕获和下载此zip文件?

yoa*_*ram 147

据我所知,正确的方法是:

import requests, zipfile, StringIO
r = requests.get(zip_file_url, stream=True)
z = zipfile.ZipFile(StringIO.StringIO(r.content))
z.extractall()
Run Code Online (Sandbox Code Playgroud)

当然你想要检查GET是否成功r.ok.

对于python 3+,将StringIO模块与io模块一起使用并使用BytesIO而不是StringIO:以下是提及此更改的发行说明.

import requests, zipfile, io
r = requests.get(zip_file_url)
z = zipfile.ZipFile(io.BytesIO(r.content))
z.extractall()
Run Code Online (Sandbox Code Playgroud)

  • 如果您想将下载的文件保存在其他位置,请将`z.extractall()`替换为`z.extractall("/ path/to/destination_directory")` (14认同)
  • 如果你只想从 url 保存文件,你可以这样做:`urllib.request.urlretrieve(url, filename)`。 (2认同)
  • 为了帮助其他人把我花了60分钟太久的时间点连接起来,您可以在上面使用`pd.read_table(z.open('filename'))`。如果您有一个包含多个文件的zip URL链接并且仅对加载一个文件感兴趣,则该功能非常有用。 (2认同)

The*_*o F 9

将 .zip 文件保存到磁盘上某个位置的超轻量级解决方案(使用 Python 3.9):

import requests

url = r'https://linktofile'
output = r'C:\pathtofolder\downloaded_file.zip'

r = requests.get(url)
with open(output, 'wb') as f:
    f.write(r.content)
Run Code Online (Sandbox Code Playgroud)


sen*_*rle 7

使用urllib2.urlopen.返回值是一个类似文件的对象,您可以read()传递给它zipfile,依此类推.


Jer*_*and 7

这篇博客文章的帮助下,我已经使它可以与Just requests。奇怪stream的是,这样我们就无需调用content大型请求,而这将需要立即处理所有请求,从而阻塞内存。在stream通过一次通过数据一个块迭代避免这一点。

url = 'https://www2.census.gov/geo/tiger/GENZ2017/shp/cb_2017_02_tract_500k.zip'
target_path = 'alaska.zip'

response = requests.get(url, stream=True)
handle = open(target_path, "wb")
for chunk in response.iter_content(chunk_size=512):
    if chunk:  # filter out keep-alive new chunks
        handle.write(chunk)
handle.close()
Run Code Online (Sandbox Code Playgroud)

  • 答案不应该依赖于链接的大部分内容。链接可能会失效,或者可以更改另一端的内容以不再回答问题。请编辑您的答案,以包括您链接指向的信息的摘要或说明。 (2认同)

ara*_*nel 6

要么使用 urllib2.urlopen,要么你可以尝试使用优秀的Requests模块并避免 urllib2 头痛:

import requests
results = requests.get('url')
#pass results.content onto secondary processing...
Run Code Online (Sandbox Code Playgroud)


Web*_*tor 6

这是我在Python 3中必须要做的工作:

import zipfile, urllib.request, shutil

url = 'http://www....myzipfile.zip'
file_name = 'myzip.zip'

with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
    shutil.copyfileobj(response, out_file)
    with zipfile.ZipFile(file_name) as zf:
        zf.extractall()
Run Code Online (Sandbox Code Playgroud)


swa*_*eek 5

我来这里是为了寻找如何保存 .bzip2 文件。让我为可能来找这个的其他人粘贴代码。

url = "http://api.mywebsite.com"
filename = "swateek.tar.gz"

response = requests.get(url, headers=headers, auth=('myusername', 'mypassword'), timeout=50)
if response.status_code == 200:
with open(filename, 'wb') as f:
   f.write(response.content)
Run Code Online (Sandbox Code Playgroud)

我只是想按原样保存文件。