from tqdm import tqdm
import requests
url = "http://download.thinkbroadband.com/10MB.zip"
response = requests.get(url, stream=True)
with open("10MB", "wb") as handle:
for data in tqdm(response.iter_content()):
handle.write(data)
from parallel_sync import wget
urls = ['http://something.png', 'http://somthing.tar.gz', 'http://somthing.zip']
wget.download('/tmp', urls)
# or a single file:
wget.download('/tmp', urls[0], filenames='x.zip', extract=True)
import urllib2,os
url = "http://download.thinkbroadband.com/10MB.zip"
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
os.system('cls')
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
如果在Windows以外的环境中运行,则必须使用“cls”之外的其他内容 . 在MAC OS X和Linux中它应该是'清除' .
7
Python 2/3的PabloG代码的改进版本:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import ( division, absolute_import, print_function, unicode_literals )
import sys, os, tempfile, logging
if sys.version_info >= (3,):
import urllib.request as urllib2
import urllib.parse as urlparse
else:
import urllib2
import urlparse
def download_file(url, dest=None):
"""
Download and save a file specified by url to dest directory,
"""
u = urllib2.urlopen(url)
scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
filename = os.path.basename(path)
if not filename:
filename = 'downloaded.file'
if dest:
filename = os.path.join(dest, filename)
with open(filename, 'wb') as f:
meta = u.info()
meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all
meta_length = meta_func("Content-Length")
file_size = None
if meta_length:
file_size = int(meta_length[0])
print("Downloading: {0} Bytes: {1}".format(url, file_size))
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = "{0:16}".format(file_size_dl)
if file_size:
status += " [{0:6.2f}%]".format(file_size_dl * 100 / file_size)
status += chr(13)
print(status, end="")
print()
return filename
if __name__ == "__main__": # Only run if this file is called directly
print("Testing with 10MB download")
url = "http://download.thinkbroadband.com/10MB.zip"
filename = download_file(url)
print(filename)
396
import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
with open('test.mp3','wb') as output:
output.write(mp3file.read())
import urllib.request
url_request = urllib.request.Request(url, headers=headers)
url_connect = urllib.request.urlopen(url_request)
len_content = url_content.length
#remember to open file in bytes mode
with open(filename, 'wb') as f:
while True:
buffer = url_connect.read(buffer_size)
if not buffer: break
#an integer value of size of written data
data_wrote = f.write(buffer)
#you could probably use with-open-as manner
url_connect.close()
import urllib2
url = "http://download.thinkbroadband.com/10MB.zip"
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
2
import os,requests
def download(url):
get_response = requests.get(url,stream=True)
file_name = url.split("/")[-1]
with open(file_name, 'wb') as f:
for chunk in get_response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
download("https://example.com/example.jpg")
22 回答
以下是在python中下载文件最常用的调用:
urllib.urlretrieve ('url_to_file', file_name)
urllib2.urlopen('url_to_file')
requests.get(url)
wget.download('url', file_name)
注意:发现
urlopen
和urlretrieve
在下载大文件(大小> 500 MB)时表现相对较差 .requests.get
将文件存储在内存中,直到下载完成 .简单但
Python 2 & Python 3
兼容的方式附带six
库:在2012年,使用python requests library
你可以运行
pip install requests
来获取它 .与其他选择相比,请求具有许多优势,因为API更简单 . 如果您必须进行身份验证,则尤其如此 . 在这种情况下,urllib和urllib2非常不直观和痛苦 .
2015年12月30日
人们对进度条表示钦佩 . 这很酷,当然 . 现在有几种现成的解决方案,包括
tqdm
:这基本上是30个月前@kvance所描述的实现 .
源代码可以是:
您可以在Python 2和3上使用PycURL .
仅为了完整起见,还可以使用
subprocess
包调用任何程序来检索文件 . 专用于检索文件的程序比像urlretrieve
这样的Python函数更强大 . 例如,wget可以递归下载目录(-R
),可以处理FTP,重定向,HTTP代理,可以避免重新下载现有文件(-nc
),aria2可以进行多连接下载,这可能会加快下载速度 .在Jupyter Notebook中,还可以使用
!
语法直接调用程序:我写了以下内容,它适用于vanilla Python 2或Python 3 .
笔记:
支持"progress bar"回调 .
下载是我网站上的4 MB测试.zip .
在python3中,您可以使用urllib3和shutil libraires . 使用pip或pip3下载它们(取决于python3是否默认)
然后运行此代码
请注意,您下载
urllib3
但在代码中使用urllib
如果速度对你很重要,我对模块
urllib
和wget
做了一个小的性能测试,关于wget
我用状态栏试了一次,没试过一次 . 我拿了三个不同的500MB文件进行测试(不同的文件 - 以消除在引擎盖下进行一些缓存的可能性) . 使用python2在debian机器上测试 .首先,这些是结果(它们在不同的运行中类似):
我执行测试的方式是使用“profile”装饰器 . 这是完整的代码:
urllib
似乎是最快的如果安装了wget,则可以使用parallel_sync .
pip install parallel_sync
Doc:https://pythonhosted.org/parallel_sync/pages/examples.html
这非常强大 . 它可以并行下载文件,在失败时重试,甚至可以在远程计算机上下载文件 .
在Python 2中,使用标准库附带的urllib2 .
这是使用库的最基本方法,减去任何错误处理 . 您还可以执行更复杂的操作,例如更改 Headers . 文档可以在here.找到
Python 3
Python 2
这可能有点晚了,但我看到了pabloG的代码并且无法帮助添加一个os.system('cls')让它看起来真棒!看看这个 :
如果在Windows以外的环境中运行,则必须使用“cls”之外的其他内容 . 在MAC OS X和Linux中它应该是'清除' .
Python 2/3的PabloG代码的改进版本:
open('test.mp3','wb')
中的wb
以二进制模式打开文件(并删除任何现有文件),因此您可以使用它而不仅仅是文本来保存数据 .您也可以通过urlretrieve获取进度反馈:
我同意Corey,urllib2比urllib更完整,如果你想做更复杂的事情,应该是使用的模块,但为了使答案更完整,如果你只想要基础知识,urllib是一个更简单的模块:
工作正常 . 或者,如果您不想处理"response"对象,您可以调用 read() 直接:
urlretrieve和requests.get很简单,但事实并非如此 . 我已经获取了几个站点的数据,包括文本和图像,以上两个可能解决了大部分任务 . 但对于更通用的解决方案,我建议使用urlopen . 由于它包含在Python 3标准库中,因此您的代码可以在任何运行Python 3的计算机上运行,而无需预先安装site-par
这个答案提供了使用Python通过http下载文件时HTTP 403 Forbidden的解决方案 . 我只尝试过请求和urllib模块,其他模块可能提供更好的东西,但这是我用来解决大多数问题的 .
使用wget模块:
为此目的在纯Python中写了wget库 . 从版本2.0开始,它被
urlretrieve
与these features一起提升 .还有一个,使用urlretrieve:
(对于Python 3,使用'import urllib.request'和urllib.request.urlretrieve)
又一个,带有“进度条”