從 HTTP/HTTPS 下載檔案時,常需在下載前獲取檔案大小(顯示進度條)、Content-Type(驗證檔案類型),並支援 Cookie 認證。
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())
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/urllib2 | requests |
|---|---|---|
| API 易用性 | 繁瑣 | 簡潔直觀 |
| 流式下載 | 需手動讀取 | 內建 iter_content |
| Cookie/Session 管理 | 手動組裝 | 自動持久化 |
| 重試/超時控制 | 需自行實現 | 內建 Retry、timeout |
| Python 3 相容 | 模組重組 (urllib.request) | 原生支援 |
tqdm 顯示下載進度。Range 標頭請求部分內容。aiohttp + asyncio 實現高併發。