alist下载

第一步 安装Alist 

https://github.com/AlistGo/alist/releases  
Windows 64位 下载 https://github.com/AlistGo/alist/releases/download/beta/alist-windows-amd64.zip

运行

alist.exe server  
在界面上可以看到密码

然后登录到

http://127.0.0.1:5244/

在后台添加百度网盘 ,打开'Web代理'

挂载路径为显示路径

根文件夹路径为百度实际路径

刷新令牌的值 从下面地址获取,也在此处登录百度网盘

https://alist.nn.ci/zh/guide/drivers/baidu.html

添加好了,设置admin密码,以便python脚本使用.

 

第二步,安装python-alist

https://libraries.io/pypi/python-alist

pip install python-alist==0.0.13.7

 

  1. 主要问题:AlistClient 对象没有 fs 属性,这是因为 alist 库的 API 结构发生了变化
  1. 依赖问题:缺少 h2 包,需要安装 httpx[http2]     

    pip install httpx[http2]
import os
import requests
from alist import AlistClient
from urllib.parse import unquote, urlparse
import sys
import argparse

sys.setrecursionlimit(20000)  # 进一步提高递归限制

def parse_args():
    parser = argparse.ArgumentParser(description='下载指定月份、周数和城市的视频文件')
    parser.add_argument('-month', type=int, required=True, help='月份,例如:2')
    parser.add_argument('-week', type=int, required=True, help='周数,例如:3')
    parser.add_argument('-city', type=str, required=True, help='城市名称,例如:台州')
    return parser.parse_args()

def download_file(url, local_path):
    response = requests.get(url, stream=True)
    total_size = int(response.headers.get('content-length', 0))
    downloaded_size = 0
    
    with open(local_path, 'wb') as f:
        for chunk in response.iter_content(chunk_size=8192):
            if chunk:
                f.write(chunk)
                downloaded_size += len(chunk)
                if total_size > 0:
                    percent = downloaded_size * 100 / total_size
                    print(f"\rDownloading: {percent:.1f}% ({downloaded_size}/{total_size} bytes)", end='')
        print()  # 换行

def create_local_path(base_url, url):
    parsed = urlparse(url)
    path = parsed.path
    # 去掉/d/前缀
    if path.startswith('/d/'):
        path = path[3:]
    # 去掉文件名后的参数
    path = path.split('?')[0]
    print(path)
    # 创建本地路径,按城市分类存储
    local_path = os.path.join('e:/uran/videos/', path)
    print(local_path)
    os.makedirs(os.path.dirname(local_path), exist_ok=True)
    return local_path


def sync_videos_to_disk(month, week, city):
    client = AlistClient("http://localhost:5244", "admin", "password")
    fs = client.fs
    fs.chdir(pan_path)

    def list_files_batch():
        """使用批量方式列出文件"""
        try:
            # 直接获取当前目录下的所有文件
            entries = fs.list()
            for entry in entries:
                if hasattr(entry, 'is_dir') and entry.is_dir:
                    try:
                        # 进入子目录
                        fs.chdir(entry.name)
                        sub_entries = fs.list()
                        # 返回上级目录
                        fs.chdir('..')
                        # 处理子目录中的文件
                        for sub_entry in sub_entries:
                            if hasattr(sub_entry, 'name') and sub_entry.name.lower().endswith('.mp4'):
                                yield sub_entry
                    except Exception as e:
                        print(f"Error accessing subdirectory {entry.name}: {str(e)}")
                        continue
                elif hasattr(entry, 'name') and entry.name.lower().endswith('.mp4'):
                    yield entry
        except Exception as e:
            print(f"Error listing directory: {str(e)}")

    try:
        # 使用新的批量遍历方式
        for file_entry in list_files_batch():
            try:
                decoded_url = unquote(file_entry.url)
                if f"第{week}周" in decoded_url and (not city or city in decoded_url):
                    print(f"Processing: {decoded_url}")
                    local_path = create_local_path("http://localhost:5244", decoded_url)
                    if os.path.exists(local_path):
                        print(f"Skipping: {decoded_url} (file already exists)")
                        continue
                    
                    print(f"Downloading: {decoded_url}")
                    download_file(decoded_url, local_path)
                    print(f"Saved to: {local_path}")
            except Exception as e:
                print(f"Error processing file {file_entry.name}: {str(e)}")
                continue

    except Exception as e:
        print(f"Error during sync: {str(e)}")

              
if __name__ == "__main__":                
    args = parse_args()
    pan_path = f'/2025年{args.month}月'
    sync_videos_to_disk(args.month, args.week, args.city)

 

posted @ 2025-01-18 21:14  meetrice  阅读(563)  评论(0)    收藏  举报