Files
37duAutomation/workflows/XQ0001-0100/XQ0047 微盟数据导出/wm_export.py
T

608 lines
26 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
@FileName: wm_export.py
@Description: XQ0047 微盟数据导出 —— 订单数据 API 导出主流程。
策略(避免导出超限 + 风控 + 减少等待):
1) 先用 queryOrderList 探测「上月1日0:00~此刻」的订单总数 totalCount;
2) 按 ceil(total / SEG_TARGET) 向上取整等分时间区间(最小化导出次数),
再用新时段逐段探测条数校验:满足阈值则定稿,超限则按
ceil(cnt / SEG_TARGET) 继续等分,直到每段都不超限;
3) 批量创建 exportOrder 导出任务(异步:不逐段等待);
4) 统一轮询 download/list 一次取回全部任务状态,全部完成后再逐段
下载 mediaUrl(zip) → 解压出 Excel;
5) 各段 Excel 的全部 sheet 数据合并到同一个工作表,输出单个最终 xlsx
(HEADER_ROWS 行表头,其余行追加)。
请求间加入随机限流 sleep,降低风控触发风险。
最终输出:一个 xlsx 文件(桌面/微盟订单导出/微盟订单_YYYYMMDD_HHMMSS.xlsx)。
登录态:由同目录 wm_login.py(或共享 share/weimob_login.py)写入
%LOCALAPPDATA%\\37duAutomation\\.sessions\\weimob_cookies.json,
本脚本只读不补登;缺失/失效时提示先运行登录脚本。
运行方式:直接运行本文件(参数全部内置,无需命令行传参)。
python wm_export.py
配置说明(改下面配置块即可):
SEG_TARGET 单段目标订单数(接口 Excel 上限 5w,此处留明细行余量)
INTERVAL 请求间限流区间(秒)
OUTPUT_DIR 输出目录,None 时默认桌面/微盟订单导出;可用环境变量 wm_export_dir 覆盖
依赖:requests openpyxl(+ wm_login 用 DrissionPage)
"""
import os
import json
import time
import math
import random
import shutil
import zipfile
import ctypes
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone, timedelta
from pathlib import Path
import requests
from openpyxl import Workbook, load_workbook
# ================== 商家配置(金色印象,其他账号改这里) ==================
BOS_ID = '4022571268153'
MERCHANT_ID = 2000527625153
VID = 6017432629153
PRODUCT_ID = 145
PRODUCT_VERSION_ID = '12010'
PRODUCT_INSTANCE_ID = 22515052153
TCODE = 'weimob'
ORDER_LIST_URL = ("https://master.weimob.com/bos/products/ecOrder/4022571268153/"
"4sidacmmkX1q2pyt1eX4sinvqste/order/order/orderlist")
QUERY_LIST_URL = "https://master.weimob.com/api3/mall/mgr/order/queryOrderList"
EXPORT_URL = "https://master.weimob.com/api3/mall/mgr/order/exportOrder"
DOWNLOAD_LIST_URL = "https://master.weimob.com/api3/merchant/backstage/service/download/list"
# ================== 输出与切分配置 ==================
OUTPUT_DIR = None # None → 桌面/微盟订单导出;可用环境变量 wm_export_dir 覆盖
FILE_PREFIX = '微盟订单' # 最终文件名前缀
SEG_TARGET = 45000 # 单段目标订单数(接口 Excel 上限 5w,留约 10% 明细行余量)
MIN_SPLIT_MS = 3600 * 1000 # 最小细分粒度(1 小时):到该粒度仍超限则直接导出尝试
INTERVAL_MIN = 3 # 请求间限流下限(秒)
INTERVAL_MAX = 5 # 请求间限流上限(秒,随机化模拟人工节奏,降低风控触发)
# ================== 运行参数(项目规范:全局重试3次) ==================
RETRY_MAX = 3 # 单段 exportOrder 最大重试次数
POLL_MAX = 180 # 统一轮询 download/list 最大次数(180×10s ≈ 30 分钟,大数据量生成较慢)
POLL_INTERVAL = 10 # 轮询间隔(秒)
DOWNLOAD_WORKERS = 4 # 并发下载线程数(CDN 单连接约 100K/s,多段并行抢带宽)
TIMEOUT = 25 # 接口请求超时(秒)
DOWNLOAD_TIMEOUT = 180 # 文件下载超时(秒,大文件 CDN 限速较慢)
HEADER_ROWS = 1 # 导出 xlsx 表头行数(合并时跳过,后续追加数据)
# ================== 共享路径 ==================
_APP_DATA_DIR = os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation')
COOKIE_FILE = os.path.join(_APP_DATA_DIR, '.sessions', 'weimob_cookies.json')
# ================== 工具函数 ==================
def _get_desktop():
"""获取真实桌面路径,适配 OneDrive 等重定向的不同电脑。"""
try:
from ctypes import wintypes
guid = wintypes.GUID(
data1=0xB4BFCC3A, data2=0xDB2C, data3=0x424C,
data4=(0xB0, 0x29, 0x7F, 0xE9, 0x9A, 0x87, 0xC6, 0x41))
func = ctypes.windll.shell32.SHGetKnownFolderPath
func.argtypes = [wintypes.GUID, wintypes.DWORD, wintypes.HANDLE,
ctypes.POINTER(ctypes.c_wchar_p)]
ptr = ctypes.c_wchar_p()
func(ctypes.byref(guid), 0, None, ctypes.byref(ptr))
return ptr.value
except Exception:
return str(Path.home() / 'Desktop')
def _get_output_dir():
"""输出目录:环境变量 wm_export_dir 优先,否则桌面/微盟订单导出。"""
env = os.getenv('wm_export_dir', '').strip()
if env:
return env
return os.path.join(_get_desktop(), '微盟订单导出')
def _sleep_interval():
"""请求间/段间限流:随机 3~5 秒,模拟人工节奏,降低风控触发概率。"""
time.sleep(random.uniform(INTERVAL_MIN, INTERVAL_MAX))
def _time_range():
"""时间范围:上月1日 00:00:00(北京时间)~ 此刻。返回毫秒时间戳 (start, end)。"""
cn_tz = timezone(timedelta(hours=8))
now = datetime.now(cn_tz)
if now.month == 1:
start_dt = datetime(now.year - 1, 12, 1, 0, 0, 0, tzinfo=cn_tz)
else:
start_dt = datetime(now.year, now.month - 1, 1, 0, 0, 0, tzinfo=cn_tz)
return int(start_dt.timestamp() * 1000), int(now.timestamp() * 1000)
def _load_cookies():
if not os.path.exists(COOKIE_FILE):
return None
with open(COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
return cookies or None
def _build_session():
"""读登录态构建 requests.Session,携带微盟鉴权票据。
微盟 api3 接口除 cookie 外,必须带以下请求头(否则 errcode=1041 fail auth):
Authorization: Bearer <saasAuthData cookie 值>
Apiclient: saas-pc
weimob-bosId: <bosId>
"""
cookies = _load_cookies()
if not cookies:
return None
token = next((c["value"] for c in cookies
if c.get("name") == "saasAuthData" and c.get("value")), "")
session = requests.Session()
session.headers.update({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Content-Type": "application/json",
"Accept": "application/json, text/plain, */*",
"Origin": "https://master.weimob.com",
"Referer": ORDER_LIST_URL,
"Authorization": f"Bearer {token}",
"Apiclient": "saas-pc",
"weimob-bosId": BOS_ID,
"x-page-route": "/bos/products/ecOrder/4022571268153/"
"4sidacmmkX1q2pyt1eX4sinvqste/order/order/orderlist",
"x-aggs-route": "products/ecOrder/4sidacmmkX1q2pyt1eX4sinvqste/order/order/orderlist",
})
for c in cookies:
domain = c.get("domain") or ""
if any(k in domain for k in ("weimob.com", "weimobwmc.com")):
session.cookies.set(c["name"], c["value"], domain=domain, path=c.get("path", "/"))
return session
# ================== 请求体模板 ==================
def _build_basic_info():
return {
"tcode": TCODE, "merchantId": MERCHANT_ID, "bosId": int(BOS_ID),
"vid": VID, "vidType": 2, "vidTypeName": "品牌", "vidTypes": [2],
"parentVid": 0, "vidPath": f"-{VID}-", "vidDeleted": False,
"vidStatus": 1, "wxOnlineStatus": 0, "onlineStoreStatus": 0,
"onlineStoreAbilityType": 1, "onlineStoreAbilityRelationVid": None,
"activeStatus": True, "vidRelation": True, "isRootVid": True,
"productId": PRODUCT_ID, "productVersionId": PRODUCT_VERSION_ID,
"productInstanceId": PRODUCT_INSTANCE_ID,
"statusCode": "in_use", "vidName": "金色印象商城", "productName": "商城",
"productVersionName": "商城连锁-PE", "overPrivilegeTime": None,
"rootVid": VID, "rootVidType": 2, "packCode": None,
}
def _query_param(start_ms, end_ms):
"""与 exportOrder 完全一致的查询条件(orderTypes 等保持一致,保证条数探测准确)。"""
return {
"orderStatuses": [], "urgePayTimeType": -1, "needBuyerHeadUrl": True,
"bizSourceTypes": [-1], "searchType": 4, "keyword": "",
"queryTime": {"type": 0, "startTime": start_ms, "endTime": end_ms},
"processVids": [], "vids": [], "orderAssign": 0, "flagRanks": [],
"channelTypes": [], "orderSources": [-1], "deliveryMode": [-1],
"orderTypes": [1, 98, 96, 11, 12], "goodsSellModes": [], "subGoodsTypes": [],
"paymentTypes": [], "deliveryTypes": [], "activities": [], "labelTypes": [],
"warehouseIds": [], "queryAmount": {"type": 1, "minAmount": "", "maxAmount": ""},
"searchScene": 0,
}
def _build_export_body(start_ms, end_ms):
"""exportOrder 请求体(exportFieldCodeList 全 null=默认导出列;仅 queryTime 动态)。"""
return {
"basicInfo": _build_basic_info(),
"operationSource": 1,
"exportFieldCodeList": [None] * 142,
"exportFormat": 1,
"exportType": 1,
"orderMenuCode": 5,
"queryParameter": _query_param(start_ms, end_ms),
"i18n": {"language": "zh-CN", "timezone": 8},
"extendInfo": {"refer": "/bos/products/ecOrder/{bosId}/{key}/order/order/orderlist", "source": 80},
}
def _build_query_body(start_ms, end_ms):
"""queryOrderList 请求体(分页,用于探测区间条数)。"""
return {
"basicInfo": _build_basic_info(),
"operationSource": 1,
"pageNum": 1,
"pageSize": 1,
"queryParameter": _query_param(start_ms, end_ms),
"i18n": {"language": "zh-CN", "timezone": 8},
"extendInfo": {"refer": "/bos/products/ecOrder/{bosId}/{key}/order/order/orderlist", "source": 80},
}
def _build_dl_body(page_size=20):
"""download/list 请求体(分页取最近导出记录,page_size 按本轮段数放大)。"""
return {
"bosId": BOS_ID,
"pageSize": page_size,
"basicInfo": {
"merchantId": MERCHANT_ID, "bosId": int(BOS_ID), "vid": VID,
"vidType": 2, "vidTypes": [2], "productId": PRODUCT_ID,
"productVersionId": PRODUCT_VERSION_ID, "productInstanceId": PRODUCT_INSTANCE_ID,
"tcode": TCODE,
},
"i18n": {"language": "zh-CN", "timezone": 8},
"extendInfo": {"refer": "/bos/products/ecOrder/{bosId}/{key}/order/order/orderlist", "source": 80},
}
# ================== 区间探测与切分 ==================
def query_count(session, start_ms, end_ms):
"""调用 queryOrderList 返回区间订单总数(失败返回 -1)。"""
try:
resp = session.post(QUERY_LIST_URL, json=_build_query_body(start_ms, end_ms), timeout=TIMEOUT)
data = resp.json() if resp.status_code == 200 else {}
if data.get("errcode") == "0":
return int((data.get("data") or {}).get("totalCount") or 0)
print(f"queryOrderList 异常:{str(data)[:200]}")
except Exception as e:
print(f"queryOrderList 请求异常:{e}")
return -1
def _split_equal(start_ms, end_ms, n):
"""把 [start_ms, end_ms] 等分为 n 段(毫秒),返回不重叠、连续覆盖的区间列表。"""
n = max(1, n)
span = end_ms - start_ms + 1
step = -(-span // n) # 向上取整,保证 n 段覆盖整区间
segments = []
cur = start_ms
for _ in range(n):
if cur + step - 1 >= end_ms:
segments.append((cur, end_ms))
break
segments.append((cur, cur + step - 1))
cur += step
return segments
def _fmt_range(a, b):
"""区间可读标签(北京时间)。"""
return (f"[{datetime.fromtimestamp(a / 1000):%m-%d %H:%M} ~ "
f"{datetime.fromtimestamp(b / 1000):%m-%d %H:%M}]")
def plan_segments(session, start_ms, end_ms):
"""按条数等分 + 逐段校验细分,最小化导出次数。
1) 探测总条数 total → 段数 n = ceil(total / SEG_TARGET),一次性等分;
2) 再用新时段逐段探测条数:<= SEG_TARGET 即定稿(不再拆);
3) 仍超限则按 ceil(cnt / SEG_TARGET) 继续等分,直到全部满足。
返回 [(seg_start_ms, seg_end_ms), ...](按时间升序)。
"""
total = query_count(session, start_ms, end_ms)
if total < 0:
return []
print(f"总区间订单数:{total}")
if total == 0:
return []
if total <= SEG_TARGET:
return [(start_ms, end_ms)]
n = math.ceil(total / SEG_TARGET)
queue = _split_equal(start_ms, end_ms, n)
print(f"按 {SEG_TARGET} 单/段向上取整,先等分为 {n} 段,逐段探测校验:")
segments = []
probe_limit = 200 # 防御:探测次数上限,避免异常数据导致无限细分
probes = 0
while queue:
probes += 1
if probes > probe_limit:
print(" 警告:细分探测次数超限,中止")
return []
a, b = queue.pop(0)
_sleep_interval()
cnt = query_count(session, a, b)
if cnt < 0:
return []
label = _fmt_range(a, b)
if cnt <= SEG_TARGET:
segments.append((a, b))
print(f" ✓ {label} 订单数={cnt} → 定稿")
continue
if b - a < MIN_SPLIT_MS:
print(f" ! {label} 订单数={cnt} 超限但已到最小粒度,直接导出尝试")
segments.append((a, b))
continue
k = math.ceil(cnt / SEG_TARGET)
print(f" ↻ {label} 订单数={cnt} 超限 → 再等分 {k} 段")
queue[0:0] = _split_equal(a, b, k) # 保持时间顺序继续校验
segments.sort()
return segments
# ================== 导出流程 ==================
def create_export_task(session, start_ms, end_ms):
"""调用 exportOrder 创建导出任务,成功返回触发时间戳(用于匹配任务)。"""
body = _build_export_body(start_ms, end_ms)
trigger_ms = int(time.time() * 1000) # 调用前记录:任务创建时间必然在此之后,匹配更稳
for attempt in range(1, RETRY_MAX + 1):
try:
resp = session.post(EXPORT_URL, json=body, timeout=TIMEOUT)
data = resp.json() if resp.status_code == 200 else {}
if data.get("errcode") == "0" and (data.get("data") or {}).get("success"):
return trigger_ms
print(f"exportOrder 第{attempt}次失败:{str(data)[:200]}")
except Exception as e:
print(f"exportOrder 第{attempt}次异常:{e}")
if attempt < RETRY_MAX:
_sleep_interval()
return None
def _parse_create_ms(item):
"""解析导出记录的 createTime 为毫秒时间戳;失败返回 None。"""
try:
dt = datetime.fromisoformat((item.get("createTime") or "").replace("Z", "+00:00"))
return dt.timestamp() * 1000
except Exception:
return None
def _task_in_window(item, lo_ms, hi_ms):
"""判断导出记录是否属于某段任务:状态成功 + 订单导出 + createTime 落在时间窗内。"""
if item.get("status") != 1 or "订单导出" not in (item.get("fileName") or ""):
return False
ct = _parse_create_ms(item)
if ct is None:
return False
return ct >= lo_ms and (hi_ms is None or ct < hi_ms)
def _fetch_download_items(session, page_size):
"""取最近导出记录列表;失败返回 None。"""
try:
resp = session.post(DOWNLOAD_LIST_URL, json=_build_dl_body(page_size), timeout=TIMEOUT)
data = resp.json() if resp.status_code == 200 else {}
if data.get("errcode") != "0":
print(f"download/list 返回异常:{str(data)[:200]}")
return None
return (data.get("data") or {}).get("items") or []
except Exception as e:
print(f"download/list 异常:{e}")
return None
def create_export_tasks(session, segments):
"""批量创建导出任务:串行调 exportOrder(随机限流),不逐段等待生成。
返回 [{'start','end','trigger_ms'}];任一段创建失败返回 None。
"""
tasks = []
for i, (a, b) in enumerate(segments, 1):
print(f" 创建任务 {i}/{len(segments)}:{_fmt_range(a, b)}")
trigger_ms = create_export_task(session, a, b)
if trigger_ms is None:
return None
tasks.append({"start": a, "end": b, "trigger_ms": trigger_ms})
if i < len(segments):
_sleep_interval()
return tasks
def wait_all_done(session, tasks):
"""统一轮询 download/list,一次请求取回全部任务状态(异步并行等待)。
任务归属:第 i 段任务 = createTime ∈ [trigger_i, trigger_{i+1}),末段上界为 None;
下界留 1 秒容差,兼容 createTime 秒级截断。
返回与 tasks 顺序一致的完成记录列表;超时返回 None(打印最近记录便于诊断)。
"""
windows = []
for i, t in enumerate(tasks):
lo = t["trigger_ms"] - 1000
hi = tasks[i + 1]["trigger_ms"] - 1000 if i + 1 < len(tasks) else None
windows.append((lo, hi))
page_size = max(20, len(tasks) + 10)
done = {}
used = set()
pending = list(range(len(tasks)))
for round_no in range(1, POLL_MAX + 1):
time.sleep(POLL_INTERVAL if round_no > 1 else 3)
items = _fetch_download_items(session, page_size)
if items is None:
continue
for idx in list(pending):
lo, hi = windows[idx]
cand = [it for it in items
if it.get("id") not in used and _task_in_window(it, lo, hi)]
if not cand:
continue
cand.sort(key=lambda it: it.get("createTime") or "")
done[idx] = cand[0]
used.add(cand[0].get("id"))
pending.remove(idx)
print(f" 任务 {idx + 1}/{len(tasks)} 已生成:{cand[0].get('fileName')}")
if not pending:
return [done[i] for i in range(len(tasks))]
print(f" 轮询 {round_no}/{POLL_MAX}:已完成 {len(done)}/{len(tasks)}")
print(" 等待超时,最近导出记录:")
for it in (_fetch_download_items(session, page_size) or [])[:10]:
print(f" id={it.get('id')} status={it.get('status')} "
f"fileName={it.get('fileName')} createTime={it.get('createTime')}")
return None
def _fix_zip_name(name):
"""修复 zip 内 GBK 编码的中文文件名乱码。"""
try:
return name.encode('cp437').decode('gbk')
except Exception:
return name
def download_and_extract(item, out_dir):
"""(并发线程内执行)用独立会话流式下载 mediaUrl(zip) → 解压出 Excel,返回 xlsx 路径。"""
media_url = item.get("mediaUrl") or ""
if not media_url:
raise RuntimeError("导出记录缺少 mediaUrl")
session = _build_session() # 独立会话:requests.Session 非线程安全,且并发下载需独立连接
if session is None:
raise RuntimeError("未找到微盟登录态")
zip_path = os.path.join(out_dir, f"导出任务_{item.get('id')}.zip")
t0 = time.time()
with session.get(media_url, timeout=DOWNLOAD_TIMEOUT, stream=True) as resp:
if resp.status_code != 200:
raise RuntimeError(f"下载失败(status={resp.status_code})")
total = 0
with open(zip_path, "wb") as f:
for chunk in resp.iter_content(1024 * 1024):
if chunk:
f.write(chunk)
total += len(chunk)
cost = max(time.time() - t0, 0.001)
print(f" 已下载:{total} 字节,耗时 {cost:.1f}s({total / cost / 1024:.0f} KB/s)")
excel_in_zip = None
with zipfile.ZipFile(zip_path) as zf:
for info in zf.infolist():
if info.is_dir():
continue
name = _fix_zip_name(info.filename)
if name.lower().endswith((".xlsx", ".xls")):
excel_in_zip = (info.filename, name)
break
if excel_in_zip is None:
raise RuntimeError("压缩包内未找到 Excel 文件")
src_in_zip, src_name = excel_in_zip
tmp = os.path.join(out_dir, src_name)
with zf.open(src_in_zip) as f_in, open(tmp, "wb") as f_out:
shutil.copyfileobj(f_in, f_out)
os.remove(zip_path)
return tmp
def merge_excels(paths, out_dir):
"""把各段 xlsx 的全部 sheet 数据合并到同一个工作表。
取第一个 sheet 的 HEADER_ROWS 行表头,其余所有 sheet 仅追加数据行;
输出单 sheet 的最终文件(write_only 流式写入,8w+ 行也不占大内存)。
"""
if not paths:
return None
final_name = f"{FILE_PREFIX}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
final_path = os.path.join(out_dir, final_name)
out_wb = Workbook(write_only=True)
out_ws = out_wb.create_sheet("订单数据")
header_written = False
total_rows = 0
for p in paths:
src = load_workbook(p, read_only=True)
for ws in src.worksheets:
# 微盟导出的 xlsx 缺 <dimension>,read_only 模式会误判为 A1:A1,必须重置尺寸
ws.reset_dimensions()
rows = ws.iter_rows(values_only=True)
if not header_written:
for _ in range(HEADER_ROWS):
row = next(rows, None)
if row is not None:
out_ws.append(list(row))
header_written = True
else:
for _ in range(HEADER_ROWS): # 跳过其余 sheet 表头
next(rows, None)
for row in rows:
if all(v is None for v in row): # 跳过空行
continue
out_ws.append(list(row))
total_rows += 1
src.close()
out_wb.save(final_path)
print(f"合并完成:单 sheet 共 {total_rows} 行数据(含表头 {total_rows + HEADER_ROWS} 行)")
# 保留各段源文件:合并异常时可人工打开核对,或供二次使用
print("各段源文件已保留:")
for p in paths:
print(f" {p}")
return final_path
# ================== 主流程 ==================
def main():
"""
微盟订单导出主流程:
探测条数 → 按条数等分并逐段校验 → 批量建导出任务 → 统一轮询 → 下载解压 → 合并一个 Excel。
返回 dict {success, excel_path, message}
"""
start_ms, end_ms = _time_range()
print(f"导出时间范围:上月1日 0:00 ~ 此刻({datetime.now().strftime('%Y-%m-%d %H:%M:%S')})")
session = _build_session()
if session is None:
return {"success": False, "excel_path": "",
"message": "未找到微盟登录态(weimob_cookies.json)。请先运行 wm_login.py 完成登录。"}
out_dir = _get_output_dir()
os.makedirs(out_dir, exist_ok=True)
segments = plan_segments(session, start_ms, end_ms)
if not segments:
return {"success": False, "excel_path": "",
"message": "区间探测失败或无订单(请检查登录态是否有效,或稍后重试)"}
print(f"最终导出段数:{len(segments)}")
# 阶段 1:批量创建导出任务(异步,不逐段等待)
print("\n批量创建导出任务:")
tasks = create_export_tasks(session, segments)
if tasks is None:
return {"success": False, "excel_path": "",
"message": "创建导出任务失败(请检查登录态或风控状态后重试)"}
# 阶段 2:统一轮询全部任务(一次请求拿全部状态,等最慢的一段)
print("\n等待全部导出任务生成:")
items = wait_all_done(session, tasks)
if items is None:
return {"success": False, "excel_path": "",
"message": "等待导出任务完成超时(已创建任务可能仍在生成,稍后可重试)"}
# 阶段 3:并发下载各段 zip(独立连接,避免单连接 CDN 限速串行等待)→ 解压 Excel
excel_paths = [None] * len(segments)
workers = min(DOWNLOAD_WORKERS, len(items))
print(f"\n并发下载 {len(items)} 段({workers} 线程):")
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(download_and_extract, it, out_dir): i
for i, it in enumerate(items)}
for fut in as_completed(futures):
i = futures[fut]
try:
excel_paths[i] = fut.result()
print(f" [段 {i + 1}/{len(segments)}] 完成:{excel_paths[i]}")
except Exception as e:
return {"success": False, "excel_path": "",
"message": f"第 {i + 1} 段下载/解压失败:{e}"}
if any(p is None for p in excel_paths):
return {"success": False, "excel_path": "", "message": "部分段下载结果缺失"}
final_path = merge_excels(excel_paths, out_dir)
if final_path is None:
return {"success": False, "excel_path": "", "message": "合并结果为空"}
return {"success": True, "excel_path": final_path,
"message": f"导出成功({len(segments)} 段合并),最终文件:{final_path}"}
if __name__ == "__main__":
result = main()
print("\n最终结果:", result)