# -*- coding: utf-8 -*- """ @FileName: material_summary_export.py @Description: 需求31 - 金蝶 K3Cloud ERP「物料收发汇总表」自动导出。 搜索打开报表 → 设置组织/日期/仓库编码 → 查询 → 引出所有页 → 下载保存。 调用关系:复用 share/erp_login.py 登录 ERP(新旧系统通用)。 运行方式:直接运行本文件(参数全部在代码内定义,无需命令行传参)。 业务配置说明(改下面配置块即可): ERP 'new' 新版 / 'old' 旧版 / 完整登录页 URL 登录账号密码 统一放项目根目录 .env(erp_login_username / erp_login_password), erp_login 自动读取,代码中不存明文 ORG_NAME 查询组织(确保过滤界面组织为该值,否则自动重新选择) STOCK_CODES 仓库编码列表,每个占一行过滤条件(或关系),可单选可多选 DATE_OPTIONS 日期选项列表(多选,逐个导出),每项支持: '60D'/'30D'/'15D'/'7D'/'3D' 今天往前推 N 天 '2026-01-01~2026-09-15' 字符串自定义起止(~ , ,空格分隔均可) ('2026-01-01', '2026-09-15') 元组自定义起止 SAVE_DIR 保存目录,None 时自动创建:桌面/采购计划报表_YYYY-MM-DD FOLDER_NAME 文件夹命名(采购计划报表+日期) FILE_PREFIX 导出文件命名前缀(物料收发汇总表_60D.xlsx) """ import os import sys import time import json import shutil from datetime import datetime, timedelta from pathlib import Path from DrissionPage import ChromiumPage from DrissionPage.common import Keys try: # 浏览器断连等致命异常需上抛,避免被通用容错吞掉空转 from DrissionPage.errors import PageDisconnectedError except Exception: PageDisconnectedError = None # ================== 业务配置(直接在此修改) ================== ERP = 'new' # 新版 criterion.erp.37du.co # 登录账号密码统一放根目录 .env:erp_login_username / erp_login_password ORG_NAME = '99.01 重庆金七象供应链管理有限公司' # 查询组织 STOCK_CODES = ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201'] # 仓库编码(可多选,或关系) DATE_OPTIONS = ['60D', '30D', '15D', '7D', '3D'] # 多选逐个导出;可混入自定义 '2026-01-01~2026-09-15' 或 ('开始','结束') SAVE_DIR = None # None → 桌面/采购计划报表_日期 FOLDER_NAME = '采购计划报表' # 文件夹命名前缀 FILE_PREFIX = '物料收发汇总表' # 导出文件命名前缀 # ================== 运行参数 ================== RETRY_MAX = 3 # 每个日期选项最大重试次数(项目规范) TIMEOUT = 15 # 元素查找超时(秒) sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'share')) from erp_login import erp_login # noqa: E402 # ================== 工具函数 ================== def _get_desktop(): """获取真实桌面路径,适配 OneDrive 等重定向的不同电脑。""" try: import ctypes 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 _is_in_viewport(el, page): """元素是否真实显示在视口内。K3 残留窗口会被移到屏幕外,此时 is_displayed 仍为 True,但其内元素点击无效——必须同时校验位置在视口内。""" try: if not el.states.is_displayed: return False w, h = el.rect.size if w <= 0 or h <= 0: return False x, y = el.rect.location vw, vh = page.run_js( 'return [window.innerWidth || document.documentElement.clientWidth,' ' window.innerHeight || document.documentElement.clientHeight];') return 0 <= x < vw and 0 <= y < vh except Exception: return False def _click_visible(page, css, timeout=TIMEOUT, by_js=False): """点击第一个在视口内可见的匹配元素,成功返回 True。浏览器断连等致命异常直接上抛。 by_js=True 用于 K3 工具栏/菜单项:物理点击只会选中文字,不触发菜单。""" end = time.time() + timeout while time.time() < end: try: for el in page.eles(css): if _is_in_viewport(el, page): el.click(by_js=True) if by_js else el.click() return True except Exception as e: if PageDisconnectedError is not None and isinstance(e, PageDisconnectedError): raise time.sleep(0.5) return False def _ele_visible(page, css, timeout=1): """元素存在、且在视口内可见才算命中(K3 过滤窗口关闭后 DOM 里仍残留隐藏/屏幕外节点)。""" end = time.time() + timeout while time.time() < end: try: for el in page.eles(css): if _is_in_viewport(el, page): return True except Exception: pass time.sleep(0.3) return False def _press_enter(page): """模拟按一次回车键。""" page.actions.key_down('Enter') page.actions.key_up('Enter') def _press_enter_in(el, page): """向指定元素直接发送回车(元素级,避免页面焦点漂移导致回车无效)。""" try: el.input(Keys.ENTER) except Exception: _press_enter(page) def _resolve_dates(option): """解析单个日期选项 → (开始日期, 结束日期, 文件标签)。 支持: '60D' 今天往前推 N 天(60/30/15/7/3) ('2026-01-01', '2026-09-15') 元组/列表自定义起止 '2026-01-01~2026-09-15' 字符串自定义起止(~ , ,空格分隔均可) DATE_OPTIONS 传列表即可多选,逐个导出。""" if isinstance(option, (list, tuple)): if len(option) == 2: begin, end = str(option[0]), str(option[1]) return begin, end, f'{begin}_{end}' raise ValueError(f'自定义日期需为(开始, 结束)两项: {option!r}') s = str(option).strip() for sep in ('~', ',', ',', ' '): if sep in s: parts = [p.strip() for p in s.split(sep) if p.strip()] if len(parts) == 2: return parts[0], parts[1], f'{parts[0]}_{parts[1]}' raise ValueError(f'自定义日期需为 开始~结束 两项: {option!r}') days = int(s.rstrip('Dd')) end = datetime.now().date() begin = end - timedelta(days=days) return begin.isoformat(), end.isoformat(), str(option) def _wait_window_title(page, keyword, timeout=TIMEOUT): """等待出现标题包含关键字的窗口,返回 True/False。""" end = time.time() + timeout while time.time() < end: t = page.ele('css:.k-window-title', timeout=1) if t and keyword in t.text: return True time.sleep(0.5) return False # ================== 报表操作 ================== def _open_report(page): """点击全局搜索 → 输入「物料收发汇总表」→ 回车 → 等待过滤界面出现。""" if not _click_visible(page, 'css:.kd-fullsearch-searchicon', timeout=10): print('[物料收发汇总表] 找不到全局搜索图标') return False time.sleep(1) sbox = page.ele('css:.kd-appplat-searchinput', timeout=5) if not sbox: print('[物料收发汇总表] 找不到搜索输入框') return False sbox.clear() sbox.input('物料收发汇总表') time.sleep(0.3) _press_enter(page) time.sleep(1.5) # 等待过滤界面(含组织字段 FSTOCKORGID)出现,限定在 .k-window 弹窗内 end = time.time() + 40 while time.time() < end: if _ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=1): print('[物料收发汇总表] 报表过滤界面已打开') return True time.sleep(0.5) # 兜底:点击搜索结果中的「物料收发汇总表」菜单项 print('[物料收发汇总表] 未自动打开,尝试点击搜索结果') els = page.eles('xpath://*[contains(text(), "物料收发汇总表")]') for el in els: try: if el.states.is_displayed and not el.closest('css:.k-window-titlebar'): el.click() time.sleep(2) if _ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=1): print('[物料收发汇总表] 报表过滤界面已打开') return True except Exception: pass return False def _close_window_by_title(page, title, timeout=3): """物理点击关闭标题包含关键字的 k-window 弹窗(K3 下载窗口等残留,关闭按钮 by_js 不触发)。 用包含匹配:实际标题可能是「文件下载」或「文档下载」,避免因标题差异关不掉。""" end = time.time() + timeout while time.time() < end: for w in page.eles('css:.k-window'): try: if not w.states.is_displayed: continue t = w.ele('css:.k-window-title', timeout=0.3) if t is None or title not in (t.text or ''): continue btn = w.ele('css:.k-window-actions .k-i-close', timeout=0.5) if btn is None: return False try: btn.click() except Exception: btn.click(by_js=True) time.sleep(0.3) return True except Exception: pass time.sleep(0.5) return False def _open_filter(page): """确保过滤界面打开(按用户明确指令): 1. 先关闭「文件下载」窗口(K3 下载完成后残留、挡在最上层) 2. 若过滤窗口已开(.k-window 内组织字段可见)→ 直接复用 3. 未开 → 点主报表「过滤」按钮重开 其余残留窗口(仓库列表等)不主动关,已通过视口判断排除干扰。 注意:过滤按钮真实 id 为 BILLMENU_TOOLBAR-tbnFilter(tbnFilter,非 tbFilter)。""" _close_window_by_title(page, '文件下载') if _ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=2): return True # 点「过滤」重开(by_js 避免 K3 菜单物理点击选中文字) if _click_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbnFilter"]', by_js=True): time.sleep(1.5) return _ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=5) return False def _set_org(page, org): """确保过滤界面组织为指定值;不是则打开多选列表重新选择(只保留目标组织)。 探针确认的结构:li.k-item > input.k-checkboxItem[name=组织名] + button.k-checkbox-button。""" # 统一限定在 .k-window 内,避免读到主界面残留的同 id 节点 disp = page.ele('css:.k-window [id*="FSTOCKORGID"] .ui-poplistedit-displayname', timeout=TIMEOUT) if disp: title = disp.attr('title') or '' if title.strip() == org: print(f'[物料收发汇总表] 组织已是: {org}') return True if not _click_visible(page, 'css:.k-window [id*="FSTOCKORGID-EDITOR"] .kd-editor-btn'): print('[物料收发汇总表] 找不到组织下拉按钮') return False time.sleep(1) # 组织多选列表弹层(_dataListdiv)独立挂载,不限定窗口; # 页面可能残留上次中断留下的隐藏弹层,必须取当前可见的那一个 dl = None for cand in page.eles('css:[id*="FSTOCKORGID-EDITOR_dataListdiv"]', timeout=TIMEOUT): try: if cand.states.is_displayed: dl = cand break except Exception: pass if dl is None: print('[物料收发汇总表] 组织多选列表未出现') return False # 输入关键字过滤列表(需回车才会过滤出结果) sbox = dl.ele('css:.kd-list-search-container input', timeout=5) if sbox: sbox.clear() sbox.input(org.split(' ', 1)[-1]) _press_enter_in(sbox, page) time.sleep(1) def _visible_lis(): """仅返回当前可见的选项行(过滤后隐藏行无位置尺寸,不可操作)。""" out = [] for li in dl.eles('css:li.k-item'): try: if li.states.is_displayed: out.append(li) except Exception: pass return out def _toggle(li, want): """want=True 勾选 / False 取消勾选;实际发生点击返回 True。""" chk = li.ele('css:input.k-checkboxItem', timeout=0.5) btn = li.ele('css:button.k-checkbox-button', timeout=0.5) if not chk or not btn: return False name = chk.attr('name') or '' try: checked = bool(chk.run_js('return this.checked;')) except Exception: return False if want == checked: return False try: btn.click() time.sleep(0.3) return True except Exception: return False # 勾选目标项 target_found = False for li in _visible_lis(): chk = li.ele('css:input.k-checkboxItem', timeout=0.5) if chk and org in (chk.attr('name') or ''): target_found = True _toggle(li, True) # 清空搜索恢复全量列表,取消其它已勾选项 if sbox: sbox.clear() _press_enter_in(sbox, page) time.sleep(1) for li in _visible_lis(): chk = li.ele('css:input.k-checkboxItem', timeout=0.5) if chk and org not in (chk.attr('name') or ''): _toggle(li, False) if not target_found: print(f'[物料收发汇总表] 组织中未找到: {org}') return False # 点弹层底部「确定」:只点一次。先弹层内找,找不到再全局找可见的兜底 ok = _click_visible(dl, 'css:.kd-multiSelectOK') if not ok: ok = _click_visible(page, 'css:.kd-multiSelectOK') if not ok: print('[物料收发汇总表] 找不到组织多选确定按钮') return False time.sleep(1) # 回读确认设置生效,防止点了确定但值没落上(限定 .k-window 内) disp = page.ele('css:.k-window [id*="FSTOCKORGID"] .ui-poplistedit-displayname', timeout=TIMEOUT) if disp and (disp.attr('title') or '').strip() == org: print(f'[物料收发汇总表] 组织已设置为: {org}') return True print(f'[物料收发汇总表] 组织设置未生效,回读不一致: {org}') return False def _visible_titles(page): """返回所有可见窗口标题文本列表。""" titles = [] try: for t in page.eles('css:.k-window-title'): try: if t.states.is_displayed: titles.append(t.text) except Exception: pass except Exception: pass return titles def _set_datepicker(page, key, date): """在 .k-window 过滤窗口内定位日期字段的 Kendo datepicker 并设值。 key: 'FBEGINDATE' / 'FENDDATE'。 K3 必须「触发日历组件」才会刷新绑定的过滤值(直接调控件 value() 无效): 方式一 真实输入日期文本 + 回车提交(Kendo 解析输入并触发 change) 方式二 打开日历面板 → 导航到目标月份 → 点选目标日期(触发 Kendo select, K3 绑定必然刷新) 每次设值后回读 input 显示值验证;失败返回 False 由外层重试,绝不假成功。""" end = time.time() + TIMEOUT last = '' while time.time() < end: for el in page.eles(f'css:.k-window [id*="{key}-EDITOR_c"]', timeout=2): # 只处理真正持有 kendoDatePicker 控件的节点 try: if not el.run_js( "return !!(window.jQuery && window.jQuery(this).data('kendoDatePicker'));"): continue except Exception: continue # ---- 方式一:真实输入 + 回车 ---- try: el.click() time.sleep(0.15) el.clear() el.input(date) time.sleep(0.2) _press_enter_in(el, page) time.sleep(0.3) val = el.run_js("return this.value || '';") if date in str(val): print(f'[物料收发汇总表] {key} 输入+回车生效(input显示 {val})') return True last = f'输入+回车 input={val!r}' except Exception as e: last = f'输入+回车异常: {e}' # ---- 方式二:打开日历点选目标日期(触发组件刷新)---- try: r = el.run_js(""" var k = window.jQuery && window.jQuery(this).data('kendoDatePicker'); if (!k) { return JSON.stringify({ok:false, why:'nok'}); } var y = +arguments[0], m = +arguments[1], d = +arguments[2]; var dt = new Date(y, m - 1, d); k.open(); if (k.calendar) { k.calendar.navigate(dt); } var cal = (k.calendar && k.calendar.element()) || window.jQuery('.k-calendar:visible').last(); var hit = null; cal.find('td').each(function () { var $td = window.jQuery(this); if ($td.hasClass('k-other-month') || $td.hasClass('k-state-other-month')) return; var $a = $td.find('a.k-link'); var txt = $a.length ? $a.text() : $td.text(); if (parseInt(txt, 10) === d) hit = $a.length ? $a : $td; }); if (hit) { hit.click(); } var v = k.value(), s = ''; if (v) { var mo = v.getMonth() + 1, da = v.getDate(); s = v.getFullYear() + '-' + (mo < 10 ? '0' + mo : mo) + '-' + (da < 10 ? '0' + da : da); } return JSON.stringify({ok: !!hit, set: s, input: this.value || ''}); """, *date.split('-')) try: r = json.loads(r) if isinstance(r, str) else r except Exception: r = {'ok': False} if r.get('ok') and date in (r.get('set') or ''): print(f'[物料收发汇总表] {key} 日历点选生效(input显示 {r.get("input")})') return True last = f'日历点选 {r}' except Exception as e: last = f'日历点选异常: {e}' time.sleep(0.5) print(f'[物料收发汇总表] {key} 日期设置失败,最后回读: {last}') return False def _set_date(page, begin, end): """设置起始/结束日期(Kendo datepicker),限定在 .k-window 过滤窗口内。""" if not _set_datepicker(page, 'FBEGINDATE', begin): print('[物料收发汇总表] 起始日期设置失败') return False if not _set_datepicker(page, 'FENDDATE', end): print('[物料收发汇总表] 结束日期设置失败') return False print(f'[物料收发汇总表] 日期: {begin} ~ {end}') return True def _click_add_row(page): """点击仓库过滤面板「新增行」(aa.md L126: )。 全局 li.k-link.kdFilterAdd 会同时匹配「主报表过滤」+「仓库过滤」两个面板, 原实现总点到主过滤那个(其行数不增加导致误判失败)。因此必须限定在仓库过滤 容器(id 含 FBeginStockId_Filter)内定位。物理点击只会选中文字,改用 JS click 触发。""" for css in ( 'xpath://li[contains(@class,"kdFilterAdd") and ancestor::div[contains(@id,"FBeginStockId_Filter")]]', 'css:[id*="FBeginStockId_Filter-FBATCHFILTERGRID_ENTRYBAR-tbAddRow"]', ): # 直接取单个元素命中即点,避免 eles 遍历整页拖慢 el = page.ele(css, timeout=2) if el is not None: try: if el.states.is_displayed: el.click(by_js=True) return True except Exception: pass return False def _row_tr(v): """上溯到包含该值输入框的条件行 (一个过滤条件一行,内含逻辑/字段/比较/值)。""" node = v for _ in range(8): try: node = node.parent() except Exception: break if node is not None and node.tag == 'tr': return node return None def _ensure_logic_or(page, v): """把指定值输入框所在行的逻辑下拉制为「或者」(OR)。 多个仓库编码之间需为或关系;行内逻辑下拉类名含 _PART_Logic_listbox,选项 并且/或者。""" tr = _row_tr(v) if tr is None: return False lg = tr.ele('css:span[role="listbox"][aria-owns*="_PART_Logic_listbox"]', timeout=2) if lg is None: return False try: cur = lg.ele('css:.k-input', timeout=1) if cur and cur.text.strip() == '或者': return True except Exception: pass try: lg.ele('css:.k-select', timeout=2).click() time.sleep(0.3) lb = page.ele('#' + lg.attr('aria-owns'), timeout=2) if lb is None: return False for it in lb.eles('css:li', timeout=2): try: if it.text.strip() == '或者': it.click() time.sleep(0.2) return True except Exception: continue except Exception as e: print(f'[物料收发汇总表] 设置逻辑为或者失败: {e}') return False return False def _diag_stock_btn(page): """仓库搜索按钮找不到时输出诊断信息,定位是过滤窗口没开还是按钮不可见。""" try: wins = [t.text for t in page.eles('css:.k-window-title') if t.states.is_displayed] print(f' [诊断] 当前可见窗口标题: {wins}') c = page.ele('css:[id*="FBEGINSTOCKID-EDITOR"]', timeout=1) print(f' [诊断] FBEGINSTOCKID-EDITOR 容器存在={bool(c)}' f' 可见={c.states.is_displayed if c else "-"}') btns = page.eles('css:[id*="FBEGINSTOCKID"] .kd-editor-btn') vis = 0 for b in btns: try: if b.states.is_displayed: vis += 1 except Exception: pass print(f' [诊断] FBEGINSTOCKID 内 .kd-editor-btn 总数={len(btns)} 可见={vis}') org_css = 'css:.k-window [id*="FSTOCKORGID"]' print(f' [诊断] 过滤窗口内(.k-window) FSTOCKORGID 可见节点: ' f'{_ele_visible(page, org_css, timeout=1)}') except Exception as e: print(f' [诊断] 异常: {e}') def _submit_query(page, with_date=None): """点主过滤界面「确定」触发查询。with_date 传 (begin, end) 时先重设日期防覆盖。 注意:[id*="_Filter-FBTNOK_c"] 也会命中仓库过滤面板的 FBeginStockId_Filter-FBTNOK_c, 用 :not 排除 + .k-window 限定,防止误点(含主界面残留节点)。 不再用 FSTOCKORGID 判断「界面关闭」:主表单存在同 id 可见节点会永远误判未关闭, 查询是否真被受理交给 _wait_progress(「查询进度」窗口是最可靠信号)。""" if with_date: if not _set_date(page, *with_date): print('[物料收发汇总表] 提交前日期重设失败') return False if not _click_visible(page, 'css:.k-window [id*="_Filter-FBTNOK_c"]:not([id*="FBeginStockId"])'): print('[物料收发汇总表] 找不到主过滤界面确定按钮') return False print('[物料收发汇总表] 已提交查询') return True def _set_stock_codes(page, codes, begin, end): """仓库编码:点搜索 → 点过滤 → 逐行新增输入(或关系)→ 确定 → 退出 → 主界面确定触发查询。 每行结构(aa.md L127):括号 + 逻辑(或) + 字段(基本信息-编码) + 比较(等于) + 值(输入后回车查询)。 新增行后填仓库编码(一行一个),并把每行逻辑设为「或者」(OR) 保证多仓库为或关系。 提交查询(点主过滤确定)前重设一次日期:仓库面板操作过程可能把过滤条件重置为默认。""" if not codes: return False # 1. 点仓库编码搜索按钮,打开仓库列表窗口(限定 .k-window 过滤窗口内) if not _click_visible(page, 'css:.k-window [id*="FBEGINSTOCKID-EDITOR"] .kd-editor-btn'): print('[物料收发汇总表] 找不到仓库编码搜索按钮') _diag_stock_btn(page) return False time.sleep(1.5) # 2. 点「过滤」打开过滤面板 if not _click_visible(page, 'css:[id*="FBeginStockId-BILLMENU_TOOLBAR-tbFilter"]'): print('[物料收发汇总表] 找不到过滤按钮') return False time.sleep(1) # 3. 逐行新增输入仓库编码,并将每行逻辑设为「或者」 val_css = 'css:[id*="FBeginStockId_Filter-FFILTERGRID"] input[placeholder*="请输入关键字"]' for i, code in enumerate(codes): # 快捷过滤网格初始为空(无默认行),每行都得先「新增行」再填值 vs = page.eles(val_css) if len(vs) <= i: added = False for _ in range(3): if _click_add_row(page): time.sleep(0.8) if len(page.eles(val_css)) > i: added = True break if not added: print(f'[物料收发汇总表] 点击新增行失败(第{i + 1}行,当前值输入框{len(vs)}个)') return False vs = page.eles(val_css) print(f'[物料收发汇总表] 当前过滤值输入框数: {len(vs)}') v = vs[i] if len(vs) > i else None if not v: print(f'[物料收发汇总表] 找不到第{i + 1}行过滤值输入框') return False v.clear() v.input(code) _press_enter_in(v, page) # 回车直接发给输入框,触发查询确认 time.sleep(0.8) _ensure_logic_or(page, v) # 保证该行逻辑为「或者」 print(f'[物料收发汇总表] 仓库条件行{i + 1}: {code}(逻辑或)') # 4. 过滤面板内「确定」 if not _click_visible(page, 'css:[id*="FBeginStockId_Filter-FBTNOK_c"]'): print('[物料收发汇总表] 找不到过滤面板确定按钮') return False time.sleep(0.8) # 5. 「退出」关闭仓库过滤窗口 _click_visible(page, 'css:[id*="FBeginStockId-BILLMENU_TOOLBAR-tbClose"]', timeout=8) time.sleep(0.8) # 6. 提交查询(提交前重设日期防仓库面板操作覆盖) return _submit_query(page, (begin, end)) def _wait_progress(page, timeout=300): """等待「查询进度」窗口出现并消失(遍历所有窗口标题)。 - 进度窗口出现但超时不消失 → 返回 False(查询失败/卡死,防止把旧报表当本次结果) - 全程未出现进度窗口 → 报表网格已渲染且连续 3 秒稳定视为快速完成(兜底) - 进度窗口消失后需连续 3 秒无进度窗口才算结束(防分阶段查询误判) 不用 FSTOCKORGID 判定界面关闭:主表单存在同 id 可见节点,不可靠。""" end = time.time() + timeout appeared = False stable = 0 while time.time() < end: in_progress = any('查询进度' in x for x in _visible_titles(page)) if in_progress: if not appeared: appeared = True print('[物料收发汇总表] 查询进度中,等待完成...') stable = 0 elif appeared: stable += 1 if stable >= 3: print('[物料收发汇总表] 查询完成') time.sleep(2) # 缓冲:数据渲染 return True else: # 进度窗口未出现:网格已渲染且稳定视为快速完成(兜底) if _ele_visible(page, 'css:.k-grid', timeout=1): stable += 1 if stable >= 3: print('[物料收发汇总表] 查询完成(进度窗口未出现)') return True else: stable = 0 time.sleep(1) print('[物料收发汇总表] 查询进度超时未结束' if appeared else '[物料收发汇总表] 未检测到查询进度且报表未渲染') return False def _export_all_pages(page): """选项 → 引出(真实鼠标悬浮展开子菜单)→ 引出所有页。 结论(现场症状):物理点击内容 span 只会『全选文字』不触发菜单;JS click 又触发不了 K3 的悬浮式嵌套子菜单。故全程用 page.actions 的真实鼠标 move_to(悬浮,不点击文字), 让子菜单展开后用 move_to+click 点中「引出所有页」;不点 span 文本,避免全选。 注意:必须复用同一个 ac=page.actions,保证光标位置连续(悬浮链不中断子菜单不收起)。""" ac = page.actions def _clickable(span): """内容 span 的父级可点击元素(a/li),避免点到文本被『全选文字』。""" try: a = span.closest('css:a') if a is not None and a.tag.lower() == 'a' and a.states.is_displayed: return a except Exception: pass try: li = span.closest('css:li') if li is not None and li.states.is_displayed: return li except Exception: pass return span # 1. 点「选项」打开配置菜单(点其 a/li,避开文本) opt = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbParamList"]', timeout=5) if opt is None or not opt.states.is_displayed: opt = page.ele('css:[id*="BILLMENU_TOOLBAR-tbParamList"]', timeout=5) if opt is None or not opt.states.is_displayed: print('[物料收发汇总表] 找不到选项按钮') return False try: ac.move_to(_clickable(opt)).click() except Exception: try: opt.click(by_js=True) except Exception: print('[物料收发汇总表] 点选项失败') return False time.sleep(1.2) # 2. 定位「引出」(splitbutton) split = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbSplitExport"]', timeout=5) if split is None or not split.states.is_displayed: split = page.ele('css:[id*="BILLMENU_TOOLBAR-tbSplitExport"]', timeout=5) if split is None or not split.states.is_displayed: print('[物料收发汇总表] 找不到导出(引出)按钮') return False def _trigger(): """悬浮目标:优先右箭头(悬浮开子菜单),无箭头则悬浮整体。""" try: ar = split.parent().ele('css:span.k-icon', timeout=1) if ar is not None and ar.states.is_displayed: return ar except Exception: pass return _clickable(split) trigger = _trigger() # 3. 悬浮展开「引出所有页」子菜单 target = None for _ in range(4): try: ac.move_to(trigger) # 真实鼠标悬浮到右箭头,子菜单展开 except Exception: pass time.sleep(1.0) t = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbButtonExportAllPage"]', timeout=2) if t is not None and t.states.is_displayed: target = t break if target is None or not target.states.is_displayed: # 悬浮未展开 → 点击箭头切换(部分版本点击才弹出) for _ in range(3): try: trigger.click() except Exception: pass time.sleep(1) t = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbButtonExportAllPage"]', timeout=2) if t is not None and t.states.is_displayed: target = t break if target is None or not target.states.is_displayed: print('[物料收发汇总表] 找不到引出所有页') return False # 4. 光标从「引出」连续移入「引出所有页」再点击(悬浮链不断,菜单不收起) try: ac.move_to(_clickable(target)) time.sleep(0.5) ac.click() except Exception: try: target.click(by_js=True) except Exception: print('[物料收发汇总表] 点击引出所有页失败') return False print('[物料收发汇总表] 已触发引出所有页') return True def _download_file(page, save_dir, new_name): """点「下载」按钮 → 等文件落盘到保存目录。 做法:把浏览器默认下载目录直接指到 save_dir,再点「下载」按钮(target=_blank 也会下载到该目录), 然后盯着文件夹等新文件出现且大小稳定(下载完成),不依赖 DrissionPage 的任务捕获,避免静默卡住。""" try: save_dir.mkdir(parents=True, exist_ok=True) page.set.download_path(str(save_dir)) page.set.when_download_file_exists('overwrite') except Exception as e: print(f'[物料收发汇总表] 设置下载目录异常: {e}') before = set(save_dir.glob('*')) if save_dir.exists() else set() before_names = {b.name for b in before} # 一次性算好,避免每秒循环重复生成 # 找可见的「下载」按钮 dl = None end = time.time() + TIMEOUT while time.time() < end: for el in page.eles('css:[id*="FDOWNLOAD_c"]'): try: if el.states.is_displayed: dl = el break except Exception: pass if dl: break time.sleep(0.5) if not dl: print('[物料收发汇总表] 找不到下载按钮') return False print('[物料收发汇总表] 点击下载按钮...') try: dl.click() except Exception: dl.click(by_js=True) # 等新文件出现且大小连续两次不变(下载完成) print('[物料收发汇总表] 等待文件下载完成...') last_size, last_name = -1, None end = time.time() + 300 while time.time() < end: new_files = [f for f in save_dir.glob('*') if f.is_file() and f.name not in before_names] if new_files: f = max(new_files, key=lambda x: x.stat().st_mtime) try: s = f.stat().st_size except Exception: s = 0 if (f.suffix not in ('.crdownload', '.tmp', '.part') and s > 0 and s == last_size and f.name == last_name): dst = save_dir / new_name if f != dst: if dst.exists(): dst.unlink() try: shutil.move(str(f), str(dst)) except Exception: dst = f print(f'[物料收发汇总表] 已保存: {dst}') _close_window_by_title(page, '文件下载') # 只关下载窗口,其余残留不主动关 return True last_size, last_name = s, f.name time.sleep(1) # 兜底:超时但确有新文件也尝试落名 new_files = [f for f in save_dir.glob('*') if f.is_file() and f.name not in before_names and f.suffix not in ('.crdownload', '.tmp', '.part')] for f in new_files: dst = save_dir / new_name if dst != f: if dst.exists(): dst.unlink() try: shutil.move(str(f), str(dst)) except Exception: dst = f print(f'[物料收发汇总表] 已保存: {dst}') _close_window_by_title(page, '文件下载') # 只关下载窗口,其余残留不主动关 return True print('[物料收发汇总表] 下载失败/超时') return False # ================== 单次导出 ================== def _reset_filter_state(page): """重试前清理脏界面状态:若查询正在进行先等其结束(ESC 会打断正常查询), 再按 ESC 关闭残留的组织下拉/过滤窗口,兜底点各面板「取消」按钮。""" end = time.time() + 120 while time.time() < end: if not any('查询进度' in x for x in _visible_titles(page)): break time.sleep(1) for _ in range(2): try: page.actions.key_down('ESC') page.actions.key_up('ESC') except Exception: pass time.sleep(0.5) _click_visible(page, 'css:[id*="FBTNCANCEL_c"]', timeout=1) time.sleep(0.5) def _run_once(page, begin, end, codes, save_dir, new_name, first): if not _open_filter(page): return False if first: # 首档:完整设置 组织 → 仓库(内部提交前重设日期并触发查询) if not _set_org(page, ORG_NAME): return False if not _set_stock_codes(page, codes, begin, end): return False else: # 后续档:组织/仓库等条件 K3 已保留,只需改日期后提交查询 if not _set_date(page, begin, end): return False if not _submit_query(page): return False if not _wait_progress(page): return False if not _export_all_pages(page): return False return _download_file(page, save_dir, new_name) # ================== 入口 ================== def main(): save_dir = Path(SAVE_DIR) if SAVE_DIR else ( Path(_get_desktop()) / f'{FOLDER_NAME}_{datetime.now():%Y-%m-%d}') save_dir.mkdir(parents=True, exist_ok=True) print(f'[物料收发汇总表] 保存目录: {save_dir}') ok, page = erp_login(ERP) if not ok: print('[物料收发汇总表] ERP 登录失败,终止') return 1 try: try: page.set.window.max() except Exception: pass time.sleep(1) if not _open_report(page): print('[物料收发汇总表] 打开报表失败,终止') return 1 failed = [] for i, option in enumerate(DATE_OPTIONS): begin, end, label = _resolve_dates(option) new_name = f'{FILE_PREFIX}_{label}.xlsx' success = False for attempt in range(1, RETRY_MAX + 1): print(f'[物料收发汇总表] [{label}] 第 {attempt}/{RETRY_MAX} 次: {begin} ~ {end}') if _run_once(page, begin, end, STOCK_CODES, save_dir, new_name, first=(i == 0)): success = True break _reset_filter_state(page) # 清掉失败留下的弹层/半填条件再重试 time.sleep(2) if not success: print(f'[物料收发汇总表] [{label}] 重试 {RETRY_MAX} 次均失败,继续下一个日期选项') failed.append(label) time.sleep(1) if failed: print(f'[物料收发汇总表] 以下日期选项导出失败: {"、".join(failed)}') return 1 finally: try: page.quit() except Exception: pass print('[物料收发汇总表] 全部导出完成') return 0 if __name__ == '__main__': main()