萬盛學電腦網

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

Python FTP/HTTP 文件下載實戰:ftplib 與 urllib 完整範例

FTP 下載與上傳

ftplib.FTP 提供完整 FTP 客戶端功能:登入、切換目錄、二進位/文本模式傳輸、斷點續傳(需手動實現)。

下載檔案


from ftplib import FTP
import sys

def ftp_download(host, user, passwd, remote_path, remote_file, local_file=None):
    local_file = local_file or remote_file
    ftp = FTP()
    ftp.set_debuglevel(2)           # 顯示詳細指令流
    ftp.connect(host)
    ftp.login(user, passwd)
    print(ftp.getwelcome())
    ftp.cwd(remote_path)
    with open(local_file, 'wb') as f:
        ftp.retrbinary(f'RETR {remote_file}', f.write, 1024)
    ftp.quit()
    print("Download complete.")

if __name__ == '__main__':
    # 命令列參數:remote_path remote_file
    if len(sys.argv) == 3:
        ftp_download('ftp.example.com', 'user', 'pass', sys.argv[1], sys.argv[2])
    else:
        ftp_download('ftp.example.com', 'user', 'pass', 'download/test/', 'test1.rar')

上傳檔案


def ftp_upload(host, user, passwd, remote_path, local_file):
    ftp = FTP()
    ftp.connect(host)
    ftp.login(user, passwd)
    ftp.cwd(remote_path)
    with open(local_file, 'rb') as f:
        ftp.storbinary(f'STOR {local_file}', f, 1024)
    ftp.quit()
  • retrbinary('RETR ...', callback, blocksize):下載,回調寫入本地檔案。
  • storbinary('STOR ...', fileobj, blocksize):上傳,讀取本地檔案發送。
  • set_debuglevel(2):除錯輸出完整 FTP 指令/回應,排錯必備。

HTTP 下載

urllib.request.urlretrieve 一行搞定簡單 GET 下載。


import urllib.request
import sys
from datetime import datetime

def http_download(url, local_file='downloaded.exe'):
    start = datetime.now()
    print(f"Start: {start}")
    urllib.request.urlretrieve(url, local_file)
    end = datetime.now()
    print(f"End: {end}")
    print(f"Elapsed: {(end - start).total_seconds():.1f}s")

if __name__ == '__main__':
    url = sys.argv[1] if len(sys.argv) == 2 else 'https://www.python.org/'
    http_download(url)

進階:大檔案流式下載、斷點續傳、進度條


import urllib.request
from tqdm import tqdm  # pip install tqdm

def http_download_stream(url, dst_path):
    req = urllib.request.Request(url, headers={'User-Agent': 'Python'})
    with urllib.request.urlopen(req) as resp, open(dst_path, 'wb') as f:
        total = int(resp.headers.get('Content-Length', 0))
        with tqdm(total=total, unit='B', unit_scale=True, desc=dst_path) as pbar:
            for chunk in iter(lambda: resp.read(8192), b''):
                f.write(chunk)
                pbar.update(len(chunk))

總結

  • FTP:ftplib 完整協議支援,適合自動化部署、鏡像站點。
  • HTTP 簡單下載:urllib.request.urlretrieve 一行足矣。
  • 生產級 HTTP 下載:requests + stream=True + tqdm 進度條、斷點續傳、重試、驗證。
copyright © 萬盛學電腦網 all rights reserved