import os import random import time from pathlib import Path import requests import urllib3 from send2trash import send2trash def create_dir(dir_path): dir_path = Path(dir_path) if not dir_path.exists(): dir_path.mkdir(parents=True, exist_ok=True) def file_to_trash(path): print(f"移动文件或目录:【{path}】到回收站") send2trash(path) def file_is_exist(path) -> bool: return Path(path).exists() def download_file(url, local_path, max_retries=3, check_file_exists=True): """下载文件并确保成功""" urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) if check_file_exists and file_is_exist(local_path): print(f"文件 {local_path} 已经存在") return for attempt in range(max_retries): try: response = requests.get(url, stream=True, timeout=10, verify=False) response.raise_for_status() os.makedirs(os.path.dirname(local_path), exist_ok=True) with open(local_path, 'wb') as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) print(f"下载成功: {url} -> {local_path}") return except Exception as e: # print(f"下载失败 (尝试 {attempt + 1}/{max_retries}): {url} -> {local_path} \n 错误: {e}") time.sleep(random.uniform(1, 3)) pass print(f"最终失败: {url}")