Files
37duAutomation/plugins/XQ0001-0100/XQ0041 新美大平台核对/data/meituan_login.py
T
puddy e4be289835 feat(xq0041): 美团/抖音核对迁出至 XQ0085,保留导表与到账统计核对(v1.3.13)
download=只导打款/团购/预订收益明细;check_settlement=到账统计核对(并台账/门店归属/更新核对统计);金色印象与金色湖畔独立浏览器档案;新增 CRM 门店映射、基础信息同步与贴总表逻辑。
2026-11-26 09:28:32 +08:00

600 lines
24 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 -*-
"""美团经营宝登录态:打开官方页面 → 预填账号密码(可选)→ 人工完成登录 → 检测进入后台。
登录策略(刻意保持“半自动”):
插件只做三件事:打开官方登录页、把界面配置的账号密码填进表单、在页面右上角挂提示。
「登录」按钮、滑块 / 图形验证码、短信验证码、选商家、选商家版本全部由人工完成。
不在代码里绕过任何验证码,也不代替用户勾选协议。
登录态复用:浏览器 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: <input id="password" placeholder="输入密码">)
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: <input id="login" placeholder="输入账号">),
// 再从密码框往上找首个含普通文本框的容器,按 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 的登录页把表单放在
<iframe class="loginFormContent" src="https://epassport.meituan.com/portal/login?..."> 里。
返回尝试顺序:统一登录域 iframe → 其它 iframe → 主页面。跨域 iframe 由 CDP 直接执行 JS。
"""
frames = []
try:
frames = list(page.get_frames() or [])
except Exception as e:
config.log(f'枚举 iframe 失败(仅试主页面):{e}', 'DEBUG')
def _rank(f):
try:
url = (f.url or '').lower()
except Exception:
return 1
if any(h in url for h in config.LOGIN_FRAME_HINTS):
config.log(f'登录相关 iframe:{url}', 'DEBUG')
return 0
return 1
frames.sort(key=lambda f: _rank(f))
return frames + [page]
def _fill_once(frame, username, password):
try:
raw = frame.run_js(_FILL_JS % {
'user': json.dumps(username, ensure_ascii=False),
'pwd': json.dumps(password, ensure_ascii=False),
})
# run_js 的返回值有两种可能:原始 JSON 字符串,或 DrissionPage 已自动解析成 dict。
if isinstance(raw, dict):
return raw
if isinstance(raw, str) and raw.strip():
try:
return json.loads(raw)
except ValueError:
config.log(f'填写结果不是 JSON:{raw[:120]}', 'DEBUG')
return None
return None
except Exception as e:
config.log(f'自动填写尝试异常:{e}', 'DEBUG')
return None
def _verify_filled(frame, password):
"""用原生 DOM 查询复核“到底填上没有”(run_js 拿不到返回值时的兜底)。"""
try:
el = frame.ele('#password', timeout=0.3)
except Exception:
return False
if not el:
return False
for getter in (lambda e: e.value, lambda e: e.attr('value')):
try:
if str(getter(el) or '') == str(password):
return True
except Exception:
continue
return False
def _switch_account_tab(frame):
try:
return str(frame.run_js(_TAB_JS) or '') == '1'
except Exception:
return False
def fill_login(page, username, password):
"""用配置的账号密码预填登录表单(**不点登录、不碰验证码、不勾协议**)。
只做一件事:填账号密码,并在页面右上角挂提示。
返回 True=已填好;False=没找到表单。
"""
deadline = time.time() + config.AUTOFILL_WAIT
tab_clicked = False
while time.time() < deadline:
for frame in _targets(page):
try:
where = (getattr(frame, 'url', '') or '').split('?')[0] or '主页面'
except Exception:
where = '主页面'
fill = _fill_once(frame, username, password)
if fill is None and _verify_filled(frame, password):
# 页面上已经填进去了,只是没读到 run_js 的返回值(跨域 iframe / 页面重渲染都会这样)
fill = {'filled': True}
config.log(f'{where} 账号密码已填入(按原生 DOM 复核确认)', 'DEBUG')
if not fill:
continue
if fill.get('reason') == 'no-password':
if not tab_clicked and _switch_account_tab(frame):
tab_clicked = True
config.log('登录页默认非账密方式,已切换到「账号登录」', 'DEBUG')
time.sleep(config.AUTOFILL_POLL)
continue
if not fill.get('filled') and not _verify_filled(frame, password):
continue
config.log(f'已在 {where} 填好账号密码,请在浏览器窗口完成登录'
'(验证码 / 选商家由你操作)')
show_login_notice(
page, '请点「登录」并完成验证',
'验证码 / 短信 / 选商家由你操作;'
f'如出现「选择商家版本」请选「我是{config.BIZ_LINE_KEYWORD}商家」',
frame=frame)
return True
time.sleep(config.AUTOFILL_POLL)
config.log(f'未找到账号密码输入框(等 {config.AUTOFILL_WAIT}s),请在浏览器窗口手动登录', 'WARN')
show_login_notice(page, '请在浏览器窗口手动登录经营宝', '请手动输入账号密码并完成验证')
return False
def _reuse_backend(page):
"""profile 里的登录态是否还能直接用。
只在后台页连续稳定 BACKEND_STABLE 秒后才算复用成功 —— /meishi 未登录也会
先停留约 20 秒才跳登录页,不能一命中就返回。
"""
deadline = time.time() + config.BACKEND_STABLE + 10
since = None
while time.time() < deadline:
state = classify(page.url)
if state == 'backend':
if since is None:
since = time.time()
elif time.time() - since >= config.BACKEND_STABLE:
return True
else:
if state in ('login', 'biz_choice'):
# 已经明确是登录/选商家页,不用再等
return False
since = None
time.sleep(config.POLL_SECONDS)
return False
def _wait_backend(page):
"""等人工完成「验证码 / 登录 / 选商家」。返回 True/False。"""
deadline = time.time() + config.LOGIN_WAIT
last_url, last_state = None, None
backend_since = None
login_hint_at = biz_hint_at = 0.0
notice_at = 0.0
while time.time() < deadline:
try:
url = page.url or ''
except Exception:
url = ''
state = classify(url)
if url != last_url:
last_url = url
config.log(f'页面状态 = {state} | {url}', 'DEBUG')
if state != last_state:
last_state = state
if state == 'login' and time.time() - login_hint_at > 30:
login_hint_at = time.time()
config.log('请在浏览器窗口内完成登录(账号密码 / 短信验证码 / 扫码均可)')
show_login_notice(page, '请在浏览器窗口完成登录',
'账号密码 / 短信 / 扫码 / 验证码都可以')
elif state == 'biz_choice' and time.time() - biz_hint_at > 30:
biz_hint_at = time.time()
config.log('账号已登录,请在页面上选择要进入的商家(不自动选,避免进错店)')
show_login_notice(page, '请选择要进入的商家',
'点选要进入的门店即可')
if state == 'backend':
if backend_since is None:
backend_since = time.time()
config.log(f'已进入商家后台,等待 {config.BACKEND_STABLE}s 确认不会再被踢回登录页…')
elif time.time() - backend_since >= config.BACKEND_STABLE:
hide_login_notice(page)
return True
else:
# 登录页是 SPA,重渲染会把浮层冲掉;每 15 秒查一次,没了就补挂
if time.time() - notice_at > 15:
notice_at = time.time()
refresh_login_notice(page)
if backend_since is not None:
config.log('又回到登录/选商家页,重新计时', 'WARN')
backend_since = None
time.sleep(config.POLL_SECONDS)
return False
def ensure_login(page, username='', password='', force_login=False):
"""确保 page 已进入商家后台;必要时预填账号密码,登录/验证码交人工。
force_login=True 时跳过落盘 Cookie 的恢复(用户要求强制重新登录)。
"""
config.log(f'打开经营宝:{config.HOME_URL}')
# 落盘 Cookie 先注回:会话 Cookie(没有 expires)浏览器一关就没了,profile 靠不住;
# 注回后再打开首页,等于把上次的登录态原样带回来。
restored = False
if not force_login:
restored = _restore_cookies(page)
page.get(config.HOME_URL)
time.sleep(config.POLL_SECONDS)
# 有些 Cookie 没带 domain,必须在 http 页面上才能注;补一次再刷新
if not force_login and not restored and _restore_cookies(page):
page.get(config.HOME_URL)
time.sleep(config.POLL_SECONDS)
if _reuse_backend(page):
_save_cookies(page) # 顺手刷新落盘备份
config.log('登录态仍有效,直接复用')
config.restore_window_mode(page) # 已进后台,不用再全屏/置顶
return True, '复用缓存登录态'
username = (username or '').strip()
password = (password or '').strip()
if username and password:
if classify(page.url) == 'biz_choice':
config.log('账号已登录,仅需选择商家(不需要再填账号密码)')
else:
config.log('未登录:填好账号密码后,请在浏览器里完成登录'
'(登录按钮 / 验证码 / 选商家由你操作)…')
fill_login(page, username, password)
elif username or password:
config.log('账号 / 密码只填了一项,本次跳过自动填写,请手工登录', 'WARN')
else:
config.log('未配置账号密码:请在浏览器窗口手工登录')
show_login_notice(page, '请在浏览器窗口登录经营宝',
'账号密码 / 验证码 / 选商家由你操作')
config.log(f'等待进入商家后台,最多 {config.LOGIN_WAIT} 秒'
f'(滑块验证码 / 选商家需在浏览器窗口人工完成)…')
if not _wait_backend(page):
return False, '登录超时(未进入商家后台)'
time.sleep(config.SETTLE_WAIT)
if classify(page.url) != 'backend':
return False, '登录态未稳定(离开后台)'
_save_cookies(page)
config.restore_window_mode(page) # 已进后台,不用再全屏/置顶
return True, '登录成功'