转载:python request下载文件时,显示进度以及网速

2021年12月19日 Jerry 2708 2023年11月6日

import requests
import time

def downloadFile(name, url):
    headers = {'Proxy-Connection':'keep-alive'}
    r = requests.get(url, stream=True, headers=headers)
    length = float(r.headers['content-length'])
    f = open(name, 'wb')
    count = 0
    count_tmp = 0
    time1 = time.time()
    for chunk in r.iter_content(chunk_size = 512):
        if chunk:
            f.write(chunk)
            count += len(chunk)
            if time.time() - time1 > 2:
                p = count / length * 100
                speed = (count - count_tmp) / 1024 / 1024 / 2
                count_tmp = count
                print(name + ': ' + formatFloat(p) + '%' + ' Speed: ' + formatFloat(speed) + 'M/S')
                time1 = time.time()
    f.close()

def formatFloat(num):
    return '{:.2f}'.format(num)

if __name__ == '__main__':
    downloadFile('360.exe', 'http://down.360safe.com/setup.exe')
$ python3 test.py
360.exe: 4.82% Speed: 1.98M/S
360.exe: 9.36% Speed: 1.86M/S
360.exe: 13.79% Speed: 1.81M/S
360.exe: 18.15% Speed: 1.79M/S
360.exe: 24.17% Speed: 2.47M/S
360.exe: 29.52% Speed: 2.19M/S
360.exe: 35.41% Speed: 2.41M/S
360.exe: 41.31% Speed: 2.42M/S
360.exe: 46.90% Speed: 2.29M/S
360.exe: 52.36% Speed: 2.24M/S
360.exe: 58.64% Speed: 2.57M/S
360.exe: 64.07% Speed: 2.23M/S
360.exe: 69.33% Speed: 2.16M/S
360.exe: 73.85% Speed: 1.85M/S
360.exe: 79.36% Speed: 2.26M/S
360.exe: 85.48% Speed: 2.51M/S
360.exe: 92.27% Speed: 2.78M/S
360.exe: 97.85% Speed: 2.28M/S

转载于:https://www.cnblogs.com/sea-stream/p/11082356.html



微信
jerry微信赞助
支付宝
jerry支付宝赞助

您尚未登录,暂时无法评论。请先 登录 或者 注册

0 人参与 | 0 条评论