简单Python HTTP下载文件,并显示下载进度条示例

56 次查看 0 条评论

一个使用requests模块进行http请求下载文件的实例,并附带友好下载进度条显示:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import requests # pip install requests
import progressbar # pip install progressbar
def download(url) :
    headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0"}
    print '\033[0;35mDownloading , Please waiting ...\033[0m'
    try :
        res = requests.get(url,headers=headers,timeout=10,stream=True,proxies=None)
    except Exception , error :
        print '\033[0;31mError: download failed.\nMessge: '+str(error)+'\033[0m'
        exit()
    if int(res.status_code) == 200 :
        header = res.headers
        size = int(header.get('Content-Length'))
        filename = os.path.basename(res.url)
        savePath = './'+str(filename)
        widgets = ['Progress: ', progressbar.Percentage(),' | ',progressbar.FileTransferSpeed(),' | ',progressbar.Timer(),' | ',progressbar.ETA(),progressbar.Bar(marker='#',left=' [',right=']')]
        pbar = progressbar.ProgressBar(widgets=widgets, maxval=size).start()
        with open(savePath,'wb') as fd:
            for chunk in res.iter_content(512): # Slice download
                fd.write(chunk)
                fd.flush()
                pbar.update(os.path.getsize(savePath))
            pbar.finish()
            fd.close()
        if size == int(os.path.getsize(savePath)) :
            print '\033[0;32mThe download is successful.\033[0m'
if __name__ == "__main__" :
    download("http://0903.beauty698.com/apk/bole_mky002.apk")

download.py

19639-yah7v256s8o.png

注意:这里没有考虑获取文件名等的一些异常处理。

Python Python

暂无评论,快来抢沙发。