萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 網路檔案下載:獲取大小、類型並儲存

需求分析

從 HTTP/HTTPS 下載檔案時,常需在下載前獲取檔案大小(顯示進度條)、Content-Type(驗證檔案類型),並支援 Cookie 認證。

使用 urllib 實作 (Python 2 風格)


import urllib2
from settings import COOKIES  # 假設設定檔提供 Cookie 字典

opener = urllib2.build_opener()
# 組裝 Cookie 標頭
cookie_header = "; ".join("%s=%s" % (k, v) for k, v in COOKIES.items())
opener.addheaders.append(('Cookie', cookie_header))

req = opener.open(link)
meta = req.info()

# 獲取檔案大小與類型
file_size = int(meta.getheaders("Content-Length")[0])
content_type = meta.getheaders('Content-Type')[0].split(';')[0]
print(file_size, content_type)

# 寫入檔案
with open(file_name, 'wb') as f:
    f.write(req.read())

現代寫法:requests 庫 (推薦)


import requests

def download_file(url, filepath, cookies=None, headers=None, chunk_size=8192):
    """流式下載,支援進度顯示、斷點續傳擴展"""
    resp = requests.get(url, cookies=cookies, headers=headers, stream=True)
    resp.raise_for_status()
    
    total_size = int(resp.headers.get('Content-Length', 0))
    content_type = resp.headers.get('Content-Type', '').split(';')[0]
    print(f'Size: {total_size}, Type: {content_type}')
    
    with open(filepath, 'wb') as f:
        for chunk in resp.iter_content(chunk_size=chunk_size):
            if chunk:
                f.write(chunk)
    return total_size, content_type

關鍵點對比

特性urllib/urllib2requests
API 易用性繁瑣簡潔直觀
流式下載需手動讀取內建 iter_content
Cookie/Session 管理手動組裝自動持久化
重試/超時控制需自行實現內建 Retry、timeout
Python 3 相容模組重組 (urllib.request)原生支援

進階功能擴展

  • 進度條:結合 tqdm 顯示下載進度。
  • 斷點續傳:使用 Range 標頭請求部分內容。
  • 驗證完整性:下載後比對 MD5/SHA256 雜湊值。
  • 非同步下載:aiohttp + asyncio 實現高併發。
copyright © 萬盛學電腦網 all rights reserved