sdk/baiduSdk/test.py

79 lines
2.3 KiB
Python
Raw Normal View History

2025-08-19 10:20:23 +00:00
import requests
import urllib.parse
import json
from configToken import ACCESS_TOKEN
from config import CATEGORY_MAP
import os
# 配置
path = "/"
access_token = ACCESS_TOKEN
headers = {'User-Agent': 'pan.baidu.com'}
# 类型映射
# -----------------------------
# 1. 获取目录下所有文件列表
# -----------------------------
list_url = (
"https://pan.baidu.com/rest/2.0/xpan/multimedia?"
f"method=listall&path={urllib.parse.quote(path)}&access_token={access_token}"
"&web=1&recursion=1&start=0&limit=100"
)
response = requests.get(list_url, headers=headers)
data = response.json()
fs_ids = [int(file_info['fs_id']) for file_info in data.get("list", [])]
if not fs_ids:
print("目录下没有文件")
exit()
# -----------------------------
# 2. 分批获取 filemetas
# -----------------------------
def chunks(lst, n):
"""把列表分成每 n 个一组"""
for i in range(0, len(lst), n):
yield lst[i:i + n]
all_file_details = []
for fs_batch in chunks(fs_ids, 100):
fsids_param = urllib.parse.quote(json.dumps(fs_batch, separators=(',', '')))
filemetas_url = (
f"https://pan.baidu.com/rest/2.0/xpan/multimedia?"
f"method=filemetas&access_token={access_token}&fsids={fsids_param}"
"&thumb=1&dlink=1&extra=1&needmedia=1&detail=1"
)
resp = requests.get(filemetas_url, headers=headers)
result = resp.json()
all_file_details.extend(result.get("list", []))
# -----------------------------
# 3. 打印文件信息(支持目录结构和类型)
# -----------------------------
for file_info in all_file_details:
# 文件名处理
server_filename = file_info.get("server_filename")
file_path = file_info.get("path")
if not server_filename:
server_filename = os.path.basename(file_path) # 从路径取最后一段
server_filename = os.path.splitext(server_filename)[0] # 去掉扩展名
size = file_info.get("size", 0)
dlink = file_info.get("dlink") # 下载链接
category = CATEGORY_MAP.get(file_info.get("category", 6), "其他") # 默认其他
is_dir = file_info.get("isdir", 0)
# 打印
print(f"文件名: {server_filename}")
print(f"路径: {file_path}")
print(f"类型: {category}{' (目录)' if is_dir else ''}")
print(f"大小: {size} 字节")
print(f"下载链接: {dlink if dlink else 'None'}")
print("=" * 50)