ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

Python 自制文件下载器

Python 自制文件下载器 1. 项目概述当你文件下载很慢时如何不用别的工具自己用趁手的工具自行搭建一个用 Python 编写一个功能完整的文件下载器。2. 环境准备本项目基于 Python 3.8 及以上版本开发无需安装任何第三方依赖。建议使用虚拟环境隔离项目避免污染全局环境。3.全部代码import requests import time def download_with_speed_retry(url: str, save_path, chunk_size8192, max_retry5): headers { User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 } retry 0 downloaded 0 total_size 0 start_time time.time() last_print_time start_time last_downloaded 0 # 如果文件已存在读取已有大小准备断点续传 try: with open(save_path,rb) as f: downloaded f.seek(0,2) except FileNotFoundError: downloaded 0 while retry max_retry: try: hdr headers.copy() if downloaded 0: hdr[Range] fbytes{downloaded}- resp requests.get(url, streamTrue, headershdr, timeout30) if resp.status_code 206: pass elif resp.status_code 200 and downloaded 0: total_size int(resp.headers.get(content-length, 0)) else: raise Exception(不支持断点续传) print(f总大小: {total_size/1024/1024:.2f} MB\n) # ab 追加写入 with open(save_path, ab) as f: for chunk in resp.iter_content(chunk_sizechunk_size): if not chunk: continue f.write(chunk) downloaded len(chunk) now time.time() delta_t now - last_print_time if delta_t 0.5: delta_bytes downloaded - last_downloaded speed_kbs delta_bytes / delta_t /1024 progress (downloaded / total_size *100) if total_size else 0 elapsed now - start_time avg_kbs downloaded / elapsed /1024 # 剩余时间计算 remain_bytes total_size - downloaded if avg_kbs 0: remain_sec remain_bytes / (avg_kbs * 1024) else: remain_sec 0 m, s divmod(remain_sec, 60) h, m divmod(m, 60) eta f{int(h):02d}:{int(m):02d}:{int(s):02d} print(f\r进度:{progress:5.2f}% | 当前:{speed_kbs:6.2f} KB/s | 平均:{avg_kbs:6.2f} KB/s | 预计剩余:{eta}, end) last_print_time now last_downloaded downloaded print(\n下载完成) return except Exception as e: retry 1 print(f\n连接异常 {e}, 重试 {retry}/{max_retry}) time.sleep(2) print(超过最大重试次数终止) if __name__ __main__: DOWNLOAD_URL 下载网页路径必须是以exe文件结尾 SAVE_FILE setup.exe # 可以改成其他的名字。 download_with_speed_retry(DOWNLOAD_URL, SAVE_FILE)4. 总结可以在此基础上继续扩展比如加入图形界面、支持 FTP 协议、实现下载队列管理等让工具更加完善。
返回列表