# -*- coding: utf-8 -*- """美团经营宝登录态:打开官方页面 → 预填账号密码(可选)→ 人工完成登录 → 检测进入后台。 登录策略(刻意保持“半自动”): 插件只做三件事:打开官方登录页、把界面配置的账号密码填进表单、在页面右上角挂提示。 「登录」按钮、滑块 / 图形验证码、短信验证码、选商家、选商家版本全部由人工完成。 不在代码里绕过任何验证码,也不代替用户勾选协议。 登录态复用:浏览器 profile 会保留会话;启动后若后台页连续稳定 BACKEND_STABLE 秒, 直接复用,不再打扰用户。profile 失效时,再尝试把落盘的 Cookie 注回浏览器; 两条都失败才退回人工登录。复用与人工登录后走同一套“稳定”判定,避免 /meishi 这类 “未登录也会先停留约 20 秒”的页面被误判成已登录。 落盘文件(仅 Cookie,按公司分文件):%LOCALAPPDATA%\37duAutomation\.sessions\ meituan_cookies.json(金色印象)/ meituan_cookies_b.json(金色湖畔) 实测登录链路(2026-10): ecom.meituan.com → 外壳,未登录也先进这里 ecom.meituan.com/meishi → 前端异步鉴权,约 20s 后才跳走,不可当已登录 .../bizaccount/login.html → 真·未登录 .../bizaccount/biz-choice.html → 账号已登录、待选商家 e.dianping.com/app/... → 选完商家进后台(登录完成,dp 商家) """ import json import os import time from .. import config def _ensure_dir(path): if path: os.makedirs(path, exist_ok=True) _COOKIE_FIELDS = { 'name', 'value', 'domain', 'path', 'expires', 'httpOnly', 'secure', 'sameSite', 'priority', 'sameParty', 'sourceScheme', 'sourcePort', 'partitionKey', } def _cookies(page): # all_info=True 才会带 expires / path / httpOnly / secure: # 只取 name/value/domain 会把持久 Cookie 的过期时间丢掉,落盘后等于降级成会话 Cookie。 try: return page.cookies(all_domains=True, all_info=True) or [] except Exception as e: config.log(f'读取 Cookies 失败:{e}', 'WARN') return [] def _save_cookies(page): """把当前浏览器 Cookie 落盘(按公司分文件),下次 profile 失效时可注回。""" cookies = _cookies(page) if not cookies: config.log('未取到任何 Cookies(登录态可能未生效)', 'WARN') return False # 只存 CDP 认的字段,避免把 size/session 这类派生字段写进备份 cookies = [{k: v for k, v in c.items() if k in _COOKIE_FIELDS} for c in cookies if isinstance(c, dict) and c.get('name')] if not cookies: return False path = config.COOKIE_FILE _ensure_dir(os.path.dirname(path)) tmp = f'{path}.tmp' with open(tmp, 'w', encoding='utf-8') as f: json.dump(cookies, f, ensure_ascii=False, indent=2) os.replace(tmp, path) config.log(f'已保存 {len(cookies)} 个 Cookies → {path}') return True def save_cookies(page): """公开的 Cookie 落盘入口(下载结束后可再刷一次,记录站点轮换后的值)。""" return _save_cookies(page) def _restore_cookies(page): """把落盘 Cookie 注回浏览器;返回是否注入成功(成功≠一定有效)。""" path = config.COOKIE_FILE if not path or not os.path.isfile(path): return False try: with open(path, encoding='utf-8') as f: cookies = json.load(f) except (OSError, ValueError) as e: config.log(f'读取 Cookies 文件失败(忽略):{e}', 'WARN') return False if not isinstance(cookies, list) or not cookies: return False now = time.time() valid = [] for c in cookies: if not isinstance(c, dict) or not c.get('name'): continue # 只保留 CDP Network.setCookie 认识的字段(Storage.getCookies 会多出 size/session 等) cookie = {k: v for k, v in c.items() if k in _COOKIE_FIELDS} exp = cookie.get('expires') try: if exp is None or float(exp) <= 0: # -1/0 = 会话 Cookie:去掉 expires,注回后仍是会话 Cookie cookie.pop('expires', None) elif float(exp) < now: continue except (TypeError, ValueError): cookie.pop('expires', None) valid.append(cookie) if not valid: return False try: page.set.cookies(valid) except Exception as e: config.log(f'恢复 Cookies 失败(改人工登录):{e}', 'WARN') return False config.log(f'已从 {path} 恢复 {len(valid)} 个 Cookies,尝试复用登录态…') return True def classify(url): """页面状态:login / biz_choice / backend / other。""" low = (url or '').strip().lower() if not low.startswith('http'): return 'other' if config.LOGIN_PAGE_HINT in low or any(h in low for h in config.PASSPORT_HINTS): return 'login' if config.BIZ_CHOICE_HINT in low: return 'biz_choice' if any(h in low for h in config.BACKEND_HINTS): return 'backend' return 'other' # ==================== 账号密码填写(只填,不提交) ==================== # 说明:只在「界面里配了账号 + 密码」时才动手;滑块/短信验证码、选商家、选版本 # 全部交人工。填不上就退回手工登录,不阻塞流程。 _FILL_JS = r''' (function () { var USER = %(user)s, PWD = %(pwd)s; function visible(el) { if (!el || !el.getBoundingClientRect) return false; var r = el.getBoundingClientRect(); if (r.width <= 2 || r.height <= 2) return false; var st = window.getComputedStyle(el); return st.display !== 'none' && st.visibility !== 'hidden' && st.opacity !== '0'; } function setValue(el, v) { // 已是目标值就不再动:轮询会反复进来,重复 setValue 会打断用户手动输入、 // 也会让页面反复校验闪红字。 if ((el.value || '') === (v || '')) return; try { var proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; var d = Object.getOwnPropertyDescriptor(proto, 'value'); if (d && d.set) d.set.call(el, v); else el.value = v; } catch (e) { el.value = v; } el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); } // 密码框:优先 id=password / placeholder 含「密码」 // (实测 epassport: ) var pwds = [].slice.call(document.querySelectorAll('input[type="password"]')).filter(visible); if (!pwds.length) return JSON.stringify({ ok: false, reason: 'no-password' }); var pwd = pwds.filter(function (el) { return (el.id || '') === 'password' || /密码/.test(el.placeholder || ''); })[0] || pwds[0]; // 账号框:先试 id=login(实测 epassport: ), // 再从密码框往上找首个含普通文本框的容器,按 placeholder/name/id 关键词取最优。 var ACC_KEY = /手机|账号|帐号|邮箱|用户名|工号|account|user|login/i; var acc = null; var direct = document.querySelector('input#login, input[name="login"], input#account, input[name="account"]'); if (direct && direct !== pwd && visible(direct)) acc = direct; if (!acc) { var cands = [], node = pwd.parentElement; for (var i = 0; i < 8 && node; i++) { var list = [].slice.call(node.querySelectorAll('input,textarea')).filter(function (el) { if (el === pwd || !visible(el) || el.disabled || el.readOnly) return false; var t = (el.getAttribute('type') || 'text').toLowerCase(); return ['text', 'tel', 'email', 'number', ''].indexOf(t) >= 0; }); if (list.length) { cands = list; break; } node = node.parentElement; } if (cands.length) { acc = cands.filter(function (el) { return ACC_KEY.test((el.placeholder || '') + (el.name || '') + (el.id || '')); })[0] || cands[0]; } } if (!acc) return JSON.stringify({ ok: false, reason: 'no-account' }); setValue(acc, USER); setValue(pwd, PWD); // 到此为止:只填账号密码。「登录」按钮、验证码、选商家全部留给用户。 return JSON.stringify({ ok: true, filled: !!(acc.value && pwd.value), filled_account: !!acc.value, filled_pwd: !!pwd.value }); })() ''' _TAB_JS = r''' (function () { var visible = function (el) { if (!el || !el.getBoundingClientRect) return false; var r = el.getBoundingClientRect(); return r.width > 2 && r.height > 2; }; var want = /^(账号登录|账号密码登录|密码登录)$/; var nodes = [].slice.call(document.querySelectorAll('button,a,span,div,li')); var hit = nodes.filter(function (el) { if (!visible(el)) return false; if (!want.test((el.textContent || '').replace(/\s+/g, ''))) return false; var inner = [].slice.call(el.querySelectorAll('button,a,span,div,li')); return !inner.some(function (c) { return want.test((c.textContent || '').replace(/\s+/g, '')); }); }); if (!hit.length) return '0'; hit[0].click(); return '1'; })() ''' # ==================== 浏览器内提示(用户只看浏览器,不看运行日志) ==================== # 任务跑在用户本机的可见浏览器里,登录期间用户眼前只有浏览器窗口,日志在壳子面板里 # 根本想不起来看。所以在登录页右上角挂一条醒目浮层,明确告诉用户“现在该你动手”, # 进入商家后台后自动移除。 _NOTICE_ID = '__xq41_login_notice' _NOTICE_JS = r'''(function () { var ID = %(id)s, OPT = %(opt)s; var old = document.getElementById(ID); if (old && old.parentNode) old.parentNode.removeChild(old); if (!OPT || !OPT.text) return '0'; var box = document.createElement('div'); box.id = ID; box.style.cssText = 'position:fixed;top:18px;right:18px;z-index:2147483647;' + 'max-width:360px;padding:14px 18px;border-radius:10px;background:#FF6A00;color:#fff;' + 'font:600 15px/1.6 "Microsoft YaHei",sans-serif;box-shadow:0 8px 28px rgba(0,0,0,.35);' + 'pointer-events:none;white-space:normal;text-align:left'; var t = document.createElement('div'); t.textContent = OPT.text; box.appendChild(t); if (OPT.sub) { var s = document.createElement('div'); s.textContent = OPT.sub; s.style.cssText = 'margin-top:6px;font-weight:400;font-size:12.5px;opacity:.92'; box.appendChild(s); } (document.body || document.documentElement).appendChild(box); return '1'; })() ''' # 最近一次提示内容:登录页刷新会把 DOM 整块换掉,靠它自动补挂 _LAST_NOTICE = {'text': '', 'sub': ''} def _try_inject(target, js): try: return str(target.run_js(js) or '') == '1' except Exception: return False def _doc_url(t): try: return (getattr(t, 'url', '') or '').split('?')[0] or '主页面' except Exception: return '?' def show_login_notice(page, text, sub='', frame=None, quiet=False): """在浏览器页面里挂提示,全局**只保留一条**。 顺序:主文档 → 填表所在文档 → 其它 iframe,第一处成功就停。 每次挂之前会先把所有文档里的旧浮层清掉 —— 否则「填表时挂在 iframe、后面更新文案 时挂在主文档」会变成 iframe 一条 + 外层一条同时显示。 """ _LAST_NOTICE['text'], _LAST_NOTICE['sub'] = text, sub opt = json.dumps({'text': text, 'sub': sub}, ensure_ascii=False) js = _NOTICE_JS % {'id': json.dumps(_NOTICE_ID), 'opt': opt} remove_js = _NOTICE_JS % {'id': json.dumps(_NOTICE_ID), 'opt': 'null'} order = [page] if frame is not None and frame is not page: order.append(frame) try: order.extend([t for t in _targets(page) if t is not page and t is not frame]) except Exception: pass # 先清干净,保证屏幕上只有一条(所有文档都清,别留历史遗留) for t in order: _try_inject(t, remove_js) hit, tried, ok_doc = 0, [], '' for t in order[:3]: # 别在一个页面的十几个 iframe 上耗时间 tried.append(_doc_url(t)) for _attempt in range(2): if _try_inject(t, js): hit = 1 ok_doc = _doc_url(t) break time.sleep(0.3) if hit: break if hit: config.log(f'已在浏览器页面挂出提示({ok_doc}):{text}') else: config.log(f'登录提示没能挂到页面上(不影响下载流程):{text};已尝试文档:{tried}', 'DEBUG' if quiet else 'WARN') return hit > 0 def _notice_alive_any(page): """任意文档里还留着提示元素?(页面重渲染会冲掉它)""" for t in [page] + [f for f in _targets(page) if f is not page]: try: if t.run_js('return !!document.getElementById(%s);' % json.dumps(_NOTICE_ID)): return True except Exception: continue return False def refresh_login_notice(page): """登录页 DOM 被整块重渲染时把提示补回来(每 15 秒查一次,见 _wait_backend)。""" text = _LAST_NOTICE['text'] if not text: return if _notice_alive_any(page): return show_login_notice(page, text, _LAST_NOTICE['sub'], quiet=True) def hide_login_notice(page): _LAST_NOTICE['text'] = '' js = _NOTICE_JS % {'id': json.dumps(_NOTICE_ID), 'opt': 'null'} _try_inject(page, js) for t in _targets(page): if t is not page: _try_inject(t, js) def _targets(page): """登录表单可能不在主文档:实测 ecom 的登录页把表单放在