示例代码:
# -*- coding:utf-8 -*-
import sys
import requests
import os
requests.packages.urllib3.disable_warnings()
def download(url, file_path):
r1 = requests.get(url, stream=True, verify=False) # stream=True将读取到达时的数据,无论数据的大小是 接收块。 如果stream=False,则数据返回为 单个块。
if r1.status_code == 403:
raise Exception("Download Failed: %s" % url)
total_size = int(r1.headers["Content-Length"])
# local file
if os.path.exists(file_path):
temp_size = os.path.getsize(file_path)
else:
temp_size = 0
print("已经下载完成的的大小 = {}".format(temp_size))
print("总大小 = {}".format(total_size))
headers = {"Range": "bytes=%d-" % temp_size}
r = requests.get(url, stream=True, verify=False, headers=headers)
with open(file_path, "ab") as f:
for chunk in r.iter_content(chunk_size=1024): # chunk_size设置大点,下载快
import time; time.sleep(1) # sleep 为了展示进度,减慢进度的更新
if chunk:
temp_size += len(chunk)
f.write(chunk)
f.flush()
done = int(50 * temp_size / total_size)
sys.stdout.write("\r[%s%s] %d%%" % ('*' * done, ' '*(50- done), 100*temp_size/total_size))
sys.stdout.flush()
print('--- end ---')
if __name__ == '__main__':
url ="http://pypi.doubanio.com/packages/2d/d3/41b3db87f262debadb153900d4e6f8d61aa87187dd6fedd855ed24e8526d/rsa-4.7.1.tar.gz" # 替换为要下载的地址
path="./rsa-4.7.1.tar.gz" # 替换为要下载的名称
download(url, path)