Python3使用requests模塊實現(xiàn)顯示下載進(jìn)度的方法詳解
本文實例講述了Python3使用requests模塊實現(xiàn)顯示下載進(jìn)度的方法。分享給大家供大家參考,具體如下:
一、配置request
1. 相關(guān)資料
請求關(guān)鍵參數(shù):stream=True。默認(rèn)情況下,當(dāng)你進(jìn)行網(wǎng)絡(luò)請求后,響應(yīng)體會立即被下載。你可以通過 stream 參數(shù)覆蓋這個行為,推遲下載響應(yīng)體直到訪問 Response.content 屬性。
tarball_url = 'https://github.com/kennethreitz/requests/tarball/master' r = requests.get(tarball_url, stream=True)
此時僅有響應(yīng)頭被下載下來了,連接保持打開狀態(tài),因此允許我們根據(jù)條件獲取內(nèi)容:
if int(r.headers['content-length']) < TOO_LONG: content = r.content ...
進(jìn)一步使用 Response.iter_content 和 Response.iter_lines 方法來控制工作流,或者以 Response.raw 從底層urllib3的 urllib3.HTTPResponse
from contextlib import closing
with closing(requests.get('http://httpbin.org/get', stream=True)) as r:
# Do things with the response here.
保持活動狀態(tài)(持久連接)
歸功于urllib3,同一會話內(nèi)的持久連接是完全自動處理的,同一會話內(nèi)發(fā)出的任何請求都會自動復(fù)用恰當(dāng)?shù)倪B接!
注意:只有當(dāng)響應(yīng)體的所有數(shù)據(jù)被讀取完畢時,連接才會被釋放到連接池;所以確保將 stream 設(shè)置為 False 或讀取 Response 對象的 content 屬性。
2. 下載文件并顯示進(jìn)度條
with closing(requests.get(self.url(), stream=True)) as response:
chunk_size = 1024 # 單次請求最大值
content_size = int(response.headers['content-length']) # 內(nèi)容體總大小
progress = ProgressBar(self.file_name(), total=content_size,
unit="KB", chunk_size=chunk_size, run_status="正在下載", fin_status="下載完成")
with open(file_name, "wb") as file:
for data in response.iter_content(chunk_size=chunk_size):
file.write(data)
progress.refresh(count=len(data))
二、進(jìn)度條類的實現(xiàn)
在Python3中,print()方法的默認(rèn)結(jié)束符(end='\n'),當(dāng)調(diào)用完之后,光標(biāo)自動切換到下一行,此時就不能更新原有輸出。
將結(jié)束符改為“\r”,輸出完成之后,光標(biāo)會回到行首,并不換行。此時再次調(diào)用print()方法,就會更新這一行輸出了。
結(jié)束符也可以使用“\d”,為退格符,光標(biāo)回退一格,可以使用多個,按需求回退。
在結(jié)束這一行輸出時,將結(jié)束符改回“\n”或者不指定使用默認(rèn)
下面是一個格式化的進(jìn)度條顯示模塊。代碼如下:
class ProgressBar(object):
def __init__(self, title,
count=0.0,
run_status=None,
fin_status=None,
total=100.0,
unit='', sep='/',
chunk_size=1.0):
super(ProgressBar, self).__init__()
self.info = "【%s】%s %.2f %s %s %.2f %s"
self.title = title
self.total = total
self.count = count
self.chunk_size = chunk_size
self.status = run_status or ""
self.fin_status = fin_status or " " * len(self.status)
self.unit = unit
self.seq = sep
def __get_info(self):
# 【名稱】狀態(tài) 進(jìn)度 單位 分割線 總數(shù) 單位
_info = self.info % (self.title, self.status,
self.count/self.chunk_size, self.unit, self.seq, self.total/self.chunk_size, self.unit)
return _info
def refresh(self, count=1, status=None):
self.count += count
# if status is not None:
self.status = status or self.status
end_str = "\r"
if self.count >= self.total:
end_str = '\n'
self.status = status or self.fin_status
print(self.__get_info(), end=end_str)
三、參考資料
http://cn.python-requests.org/en/latest/user/advanced.html
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python面向?qū)ο蟪绦蛟O(shè)計入門與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
- 淺析Python requests 模塊
- Python使用requests模塊爬取百度翻譯
- Python grequests模塊使用場景及代碼實例
- Python requests模塊安裝及使用教程圖解
- Python requests模塊cookie實例解析
- python爬蟲開發(fā)之Request模塊從安裝到詳細(xì)使用方法與實例全解
- Python3離線安裝Requests模塊問題
- python爬蟲 基于requests模塊的get請求實現(xiàn)詳解
- python爬蟲 基于requests模塊發(fā)起ajax的get請求實現(xiàn)解析
- python利用re,bs4,requests模塊獲取股票數(shù)據(jù)
- Python實現(xiàn)使用request模塊下載圖片demo示例
- python request 模塊詳細(xì)介紹
相關(guān)文章
python進(jìn)行數(shù)據(jù)預(yù)處理的4個重要步驟
在數(shù)據(jù)科學(xué)項目中,數(shù)據(jù)預(yù)處理是最重要的事情之一,本文詳細(xì)給大家介紹python進(jìn)行數(shù)據(jù)預(yù)處理的4個重要步驟:拆分訓(xùn)練集和測試集,處理缺失值,處理分類特征和進(jìn)行標(biāo)準(zhǔn)化處理,需要的朋友可以參考下2023-06-06
python數(shù)據(jù)可視化pygal模擬擲骰子實現(xiàn)示例
這篇文章主要為大家介紹了python數(shù)據(jù)可視化pygal模擬擲骰子實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
python數(shù)據(jù)分析之DataFrame內(nèi)存優(yōu)化
pandas處理幾百兆的dataframe是沒有問題的,但是我們在處理幾個G甚至更大的數(shù)據(jù)時,就會特別占用內(nèi)存,對內(nèi)存小的用戶特別不好,所以對數(shù)據(jù)進(jìn)行壓縮是很有必要的,本文就介紹了python DataFrame內(nèi)存優(yōu)化,感興趣的可以了解一下2021-07-07
Pycharm創(chuàng)建python文件自動添加日期作者等信息(步驟詳解)
這篇文章主要介紹了Pycharm創(chuàng)建python文件自動添加日期作者等信息(步驟詳解),本文分步驟給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02

