python使用requests模块下载文件并获取进度提示
一、概述
使用python3写了一个获取某网站文件的小脚本,使用了requests模块的get方法得到内容,然后通过文件读写的方式保存到硬盘
同时需要实现下载进度的显示
二、代码实现
安装模块
pip3 install requests tqdm
test.py 完整代码如下:

# !/usr/bin/python3 # -*- coding: utf-8 -*- import os from urllib.request import urlopen import requests from tqdm import tqdm def download_from_url(url, dst): """ @param: url to download file @param: dst place to put the file :return: bool """ # 获取文件长度 try: file_size = int(urlopen(url).info().get('Content-Length', -1)) except Exception as e: print(e) print("错误,访问url: %s 异常" % url) return False # 判断本地文件存在时 if os.path.exists(dst): # 获取文件大小 first_byte = os.path.getsize(dst) else: # 初始大小为0 first_byte = 0 # 判断大小一致,表示本地文件存在 if first_byte >= file_size: print("文件已经存在,无需下载") return file_size header = {"Range": "bytes=%s-%s" % (first_byte, file_size)} pbar = tqdm( total=file_size, initial=first_byte, unit='B', unit_scale=True, desc=url.split('/')[-1]) # 访问url进行下载 req = requests.get(url, headers=header, stream=True) try: with(open(dst, 'ab')) as f: for chunk in req.iter_content(chunk_size=1024): if chunk: f.write(chunk) pbar.update(1024) except Exception as e: print(e) return False pbar.close() return True if __name__ == '__main__': url = "https://dl.360safe.com/360/inst.exe" download_from_url(url, "inst.exe")
效果如下:
本文参考链接:
分类:
python 运维开发
标签:
爬虫
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)