# -*- coding: utf-8 -*- """浏览器:一次运行共用一个可见浏览器(登录 + 三张表下载都复用它,避免反复开关)。 独立固定用户目录 %LOCALAPPDATA%\\37duAutomation\\browser_sessions\\xq0041, 登录态跨次保留,不占用用户日常 Chrome 配置。 """ from DrissionPage import ChromiumPage, ChromiumOptions from .. import config def open_page(): co = ChromiumOptions() if config.HEADLESS: co.headless() co.set_argument('--start-maximized') co.set_pref('credentials_enable_service', False) co.set_pref('profile.password_manager_enabled', False) profile = config.get_browser_profile_dir() import os os.makedirs(profile, exist_ok=True) co.set_user_data_path(profile) config.log(f'浏览器用户目录:{profile}', 'DEBUG') page = ChromiumPage(co) if not config.HEADLESS: # 登录要人工操作(账密/短信/扫码/选商家),全屏 + 置顶避免被其它窗口挡住 config.apply_window_mode(page) return page def close_page(page): try: page.quit() except Exception: pass def xhr(page, method, url, payload=None): """页面上下文同步 XHR:mtgsig/yodaReady 由页面上的 Yoda(H5guard) SDK 自动补。 返回 (status:int, text:str)。 """ import json as _json body_js = 'null' headers_js = '' if payload is not None: body_js = 'JSON.stringify(' + _json.dumps(payload, ensure_ascii=False) + ')' headers_js = "x.setRequestHeader('Content-Type','application/json');" js = ''' try { var x = new XMLHttpRequest(); x.open('%s', '%s', false); x.withCredentials = true; %s x.send(%s); return x.status + '||' + String(x.responseText || ''); } catch (e) { return 'ERR||' + e; } ''' % (method.upper(), url, headers_js, body_js) raw = page.run_js(js) if not raw or '||' not in str(raw): return 0, f'返回值异常:{str(raw)[:200]}' status, _, text = str(raw).partition('||') try: return int(status), text except Exception: return 0, text def api_json(page, method, url, payload=None): import json as _json status, text = xhr(page, method, url, payload) name = url.split('/')[-1].split('?')[0] if status != 200: config.log(f'{name} 请求失败:status={status} {text[:200]}', 'WARN') return None try: return _json.loads(text) except Exception as e: config.log(f'{name} 返回非 JSON:{e} | {text[:200]}', 'WARN') return None def download_file(link, save_path): """S3 预签名 URL 直下(无需 Cookie / mtgsig)。返回字节数,失败 0。""" import os import time import requests headers = { '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'), 'Accept': '*/*', } os.makedirs(os.path.dirname(save_path), exist_ok=True) for attempt in range(1, config.RETRY_MAX + 1): try: resp = requests.get(link, headers=headers, timeout=300, stream=True) if resp.status_code != 200: config.log(f'下载失败:HTTP {resp.status_code}({attempt}/{config.RETRY_MAX})', 'WARN') time.sleep(2) continue tmp = save_path + '.part' with open(tmp, 'wb') as f: for chunk in resp.iter_content(128 * 1024): if chunk: f.write(chunk) os.replace(tmp, save_path) size = os.path.getsize(save_path) if size < 1024: config.log(f'文件异常小({size} 字节),重试 {attempt}/{config.RETRY_MAX}', 'WARN') time.sleep(2) continue return size except Exception as e: config.log(f'下载异常:{e}({attempt}/{config.RETRY_MAX})', 'WARN') time.sleep(2) return 0 def read_xlsx_summary(path): """读 sheet 名/行列数,确认文件有效。""" try: from openpyxl import load_workbook wb = load_workbook(path, read_only=True, data_only=True) ws = wb.worksheets[0] info = {'sheet': ws.title, 'rows': ws.max_row, 'cols': ws.max_column} wb.close() return info except Exception as e: return {'error': str(e)}