import requests import os from tqdm import tqdm def get_token(alist_url, username, password): """登录并获取token""" login_url = f"{alist_url}/api/auth/login" data = { "username": username, "password": password } response = requests.post(login_url, json=data) if response.status_code == 200: return response.json()["data"]["token"] raise Exception("登录失败") def download_file(alist_url, token, file_path, save_path): """下载文件""" headers = { "Authorization": token } # 获取文件下载链接 fs_url = f"{alist_url}/api/fs/get" params = {"path": file_path} response = requests.get(fs_url, headers=headers, params=params) if response.status_code == 200: download_url = response.json()["data"]["raw_url"] # 获取文件大小 response = requests.get(download_url, stream=True) total_size = int(response.headers.get('content-length', 0)) # 在进度条之前只显示一次文件名 print(f"\n正在下载: {os.path.basename(file_path)}") # 使用tqdm创建进度条,不再显示文件名 progress_bar = tqdm( total=total_size, unit='iB', unit_scale=True, leave=True, ncols=100, bar_format='{percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]' # 移除desc ) # 下载文件并更新进度条 with open(save_path, 'wb') as f: for chunk in response.iter_content(chunk_size=8192): size = f.write(chunk) progress_bar.update(size) progress_bar.close() # 下载完成后再打印一个换行 print("") if total_size != 0 and progress_bar.n != total_size: return False return True return False def list_directory(alist_url, token, dir_path): """列出目录内容""" headers = {"Authorization": token} fs_list_url = f"{alist_url}/api/fs/list" params = {"path": dir_path} response = requests.post(fs_list_url, headers=headers, json=params) if response.status_code == 200: return response.json()["data"]["content"] return [] def recursive_download(alist_url, token, current_path, base_save_path, target_keyword, level=0): """递归遍历目录并下载符合条件的文件""" items = list_directory(alist_url, token, current_path) indent = " " * level print(f"{indent} 标签:get,url,alist,token,path,response,下载 From: https://www.cnblogs.com/meetrice/p/18678876