从 URL 下载返回的 Zip 文件 [英] Download Returned Zip file from URL
问题描述
如果我有一个 URL,当在 Web 浏览器中提交时,会弹出一个对话框来保存 zip 文件,我将如何在 Python 中捕获和下载此 zip 文件?
If I have a URL that, when submitted in a web browser, pops up a dialog box to save a zip file, how would I go about catching and downloading this zip file in Python?
推荐答案
如果可用,大多数人建议使用 requests
,而 requests
文档 建议使用此方法从 url 下载和保存原始数据:
Most people recommend using requests
if it is available, and the requests
documentation recommends this for downloading and saving raw data from a url:
import requests
def download_url(url, save_path, chunk_size=128):
r = requests.get(url, stream=True)
with open(save_path, 'wb') as fd:
for chunk in r.iter_content(chunk_size=chunk_size):
fd.write(chunk)
由于答案询问下载和保存 zip 文件,因此我没有详细介绍有关阅读 zip 文件的内容.请参阅以下众多答案之一以了解可能性.
Since the answer asks about downloading and saving the zip file, I haven't gone into details regarding reading the zip file. See one of the many answers below for possibilities.
如果由于某种原因您无权访问 requests
,您可以使用 urllib.request
代替.它可能不像上面那样健壮.
If for some reason you don't have access to requests
, you can use urllib.request
instead. It may not be quite as robust as the above.
import urllib.request
def download_url(url, save_path):
with urllib.request.urlopen(url) as dl_file:
with open(save_path, 'wb') as out_file:
out_file.write(dl_file.read())
最后,如果你还在使用 Python 2,你可以使用 urllib2.urlopen
.
Finally, if you are using Python 2 still, you can use urllib2.urlopen
.
from contextlib import closing
def download_url(url, save_path):
with closing(urllib2.urlopen(url)) as dl_file:
with open(save_path, 'wb') as out_file:
out_file.write(dl_file.read())
这篇关于从 URL 下载返回的 Zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!