美文网首页
使用requests下载文件并显示网速和下载进度

使用requests下载文件并显示网速和下载进度

作者: Moneys | 来源:发表于2018-05-22 10:47 被阅读0次
import requests

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')

请根据实际情况组装headers

相关文章

网友评论

      本文标题:使用requests下载文件并显示网速和下载进度

      本文链接:https://www.haomeiwen.com/subject/yzhhjftx.html