• python使用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")
    View Code

    效果如下:

    本文参考链接:

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

  • 相关阅读:
    VIM 配色方案,先保存一下
    ncurses库的介绍与安装
    win7 设置双屏壁纸
    3. Vim入门教程
    2. Vim 概念扫盲
    把Debian 设置中文环境
    静态代码块和构造代码块的区别
    jsp详解(3个指令、6个动作、9个内置对象、11个隐式对象)
    JVM虚拟机详解
    Java 的内置对象
  • 原文地址:https://www.cnblogs.com/xiao987334176/p/12655015.html
Copyright © 2020-2023  润新知