python 之实现断点下载与下载进度条
一、效果图
二、进度条代码
__author__ = 'Yang' import os import time from threading import Thread '''下载进度条''' class Down_progress(object): def __init__(self, total, init_size, dst): # 文件总大小 self.total = total # 下载大小 self.init_size = init_size # 文件保存路径 self.dst = dst def start(self): def start(): start_time = time.time() print('[文件大小]:%.2f MB' % ((self.total - self.init_size) / 1024 / 1024)) while self.init_size < self.total: speed_str = '' if os.path.exists(self.dst): # 计算下载率 start = self.init_size time.sleep(1) down_speed = (self.init_size - start) / 1024 if down_speed > 1024: speed_str = '%.2f MB/s' % (down_speed / 1024) else: speed_str = '%.2f kb/s' % down_speed print('\r' + '[下载进度]:[%s]%.2f%%,下载速度:%s' % ('#' * int(self.init_size * 50 / self.total), float(self.init_size / self.total * 100), speed_str), end = '') # 计算下载时间 offset_time = time.time() - start_time if offset_time > 60: offset_time = '%.2f 分钟' % (offset_time / 60) else: offset_time = '%.2f 秒' % offset_time print('\n' + '下载完成,耗时:%s' % offset_time) th = Thread(target = start) th.start() ''' 更新下载大小''' def update(self, size): self.init_size += size
三、断点下载例子
import requests, re, os from threading import Thread from down_progress import * host = "http://www.8080s.net" url = "http://www.8080s.net/movie/32088" headers = {'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1'} ''' 断点下载''' def down(url, dst): try: response = requests.get(url, stream=True, verify=False) file_size = int(response.headers['content-length']) if os.path.exists(dst): first_size = os.path.getsize(dst) else: first_size = 0 if file_size <= first_size: return headers['Range'] = "bytes=%d-" % (first_size, ) print("开始下载:"+url) res = requests.get(url, stream=True, headers=headers, verify=False) with open(dst, "ab") as f: dp = Down_progress(file_size, first_size, dst) dp.start() chunk_size = 1024 for chunk in res.iter_content(chunk_size = chunk_size): if chunk: f.write(chunk) dp.update(chunk_size) except Exception as e: print(e) if __name__ == '__main__': res = requests.get(url) content = res.text a = re.findall(r"<a[^>]*\s+href=[\'\"]?([^\'\"]*)[\'\"]?[^>]*\s+>.*<\/", content) down(a[0], './%s' % os.path.basename(a[0]))