广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python使用requests模块下载文件并获取进度提示
  • 869
分享到

python使用requests模块下载文件并获取进度提示

进度模块提示 2023-01-31 08:01:06 869人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

使用python3写了一个获取某网站文件的小脚本,使用了requests模块的get方法得到内容,然后通过文件读写的方式保存到硬盘同时需要实现下载进度的显示 安装模块pip3 install requests&

使用python3写了一个获取某网站文件的小脚本,使用了requests模块的get方法得到内容,然后通过文件读写的方式保存到硬盘
同时需要实现下载进度的显示

 

安装模块

pip3 install requests tqdm

test.py 完整代码如下:

#!/usr/bin/env 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:
        first_byte = 0
    if first_byte >= file_size:
        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")

 

效果如下:

1.gif

 

本文参考链接:

Https://www.zhihu.com/question/41132103/answer/279584095


--结束END--

本文标题: python使用requests模块下载文件并获取进度提示

本文链接: https://www.lsjlt.com/news/193673.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作