【Python】requests下载+进度条

时间:2020-08-01
本文章向大家介绍【Python】requests下载+进度条,主要包括【Python】requests下载+进度条使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/8/1 13:05
# @Author  : Shuranima
# @File    : Single_thread_download.py
#

import os
import requests
from tqdm import tqdm
import time

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0'
}

def down_from_url(url, dst):
        response = requests.get(url, headers=headers, stream=True)  # (1)
        file_size = int(response.headers['content-length']) # (2)
        if os.path.exists(dst):
            first_byte = os.path.getsize(dst)  # (3)
        else:
            first_byte = 0
        if first_byte >= file_size: # (4)
            return file_size

        header = {"Range": f"bytes={first_byte}-{file_size}"}

        pbar = tqdm(total=file_size, initial=first_byte, unit='B', unit_scale=True, desc=dst)
        req = requests.get(url, headers=header, stream=True)  # (5)
        with open(dst, 'ab') as f:
            for chunk in req.iter_content(chunk_size=1024):     # (6)
                if chunk:
                    f.write(chunk)
                    pbar.update(1024)
        pbar.close()
        return file_size
def download(url, path, filename): if not os.path.exists(path): os.makedirs(path) print('地址:' + url) print('开始下载,' + filename) start_time = time.time() down_from_url(url, path + '/' + filename) end_time = time.time() print(f"下载完成,共花费了{end_time - start_time}")

 

$flag 上一页 下一页

上一篇:vue面试

下一篇:Java命名规范