requests 使用 stream 流形式下載文件


requests stream=True

import time
import requests

download_url = ''
start_time = time.time()
file_name = 'video.mp4'  # 文件名稱

# 以流形式下載文件
result = requests.get(download_url, stream=True)
size = 0  # 已下載文件的大小
chunk_size = 1024 * 1024  # 每次下載數據的大小:單位字節 1024:1KB 1024*1024:1MB
content_size = int(result.headers["content-length"])  # 文件總大小:單位字節
try:
    if result.status_code == 200:
        with open(file_name, 'wb') as video_file:
            # 當把get函數的stream參數設置成True時,它不會立即開始下載
            # 使用iter_content或iter_lines遍歷內容或訪問內容屬性時才開始下
            # 每次下載chunk_size大小的內容寫入文件
            for data in result.iter_content(chunk_size=chunk_size):
                video_file.write(data)
                size += len(data)  # 已下載文件的大小
                # 已完成的百分比
                percentage = size / content_size
                # 打印進度條
                print('\r',
                      f'《 {file_name} 》:%.2fMB\t' % (content_size / 1024 / 1024),
                      '下載進度:[%-50s%.2f%%]耗時:%.1fs' % (
                          '>' * int(50 * percentage), percentage * 100, time.time() - start_time),
                      end='')
except Exception as e:
    print('下載出錯', e)





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM