Files
37duAutomation/plugins/XQ0001-0100/XQ0041 新美大平台核对/data/meituan_login.py
T
puddy 911fd7661f feat(xq0041): 经营宝登录改人工点确认 + 双公司独立档案与执行模式拆分(1.3.9)
- 登录改为自动填账号密码并勾选用户协议,页面右上角浮层提示人工点「登录」(按钮、滑块/短信、选门店仍人工),登录一次长期复用

- 金色印象 / 金色湖畔各自独立浏览器档案与调试端口(xq0041 / xq0041_b,9222 / 9333),避免同浏览器反复切号触发风控

- 执行模式拆 full(只导金色印象 + 并台账 + 更新核对统计)/ export_only(按范围勾选各导一份,不写表),湖畔报表文件名带「金色湖畔_」前缀;UI 同步重建
2026-11-06 15:52:10 +08:00

793 lines
33 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 -*-
"""美团经营宝登录态:打开官方页面 → 自动/人工登录(含选商家)→ 检测完成 → 落盘 cookies/票据。
账号密码预填(可选):插件界面配置了账号 + 密码时,用页面上下文 JS 填好账号密码、
勾上「用户协议」,**不点登录**;并在浏览器页面右上角挂一条醒目浮层,提示用户
到浏览器里点「登录」(滑块 / 图形验证码 / 短信验证码 / 选商家同样交人工)。
未配置账号密码或填不上 → 退回手工登录,不影响业务。
为什么通知走页面浮层而不是日志:任务跑在用户自己机器的可见浏览器里,登录期间
用户眼前只有浏览器,日志在壳子面板里基本不会去看。
为什么不用 requests 校验:经营宝所有业务接口带 mtgsig 动态签名(页面 H5guard 秒级生成),
requests 复刻必然 403。登录态有效性只由浏览器判定,取数也一律在页面上下文发请求。
实测登录链路(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)
def _atomic_write(path, text):
_ensure_dir(os.path.dirname(path))
tmp = f'{path}.tmp'
with open(tmp, 'w', encoding='utf-8') as f:
f.write(text)
os.replace(tmp, path)
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'
def _cookies(page):
try:
return page.cookies(all_domains=True) or []
except Exception as e:
config.log(f'读取 Cookies 失败:{e}', 'WARN')
return []
def _platform_cookie_header(cookies):
skip = ('passport', 'certificates', 'report', 'lx', 'dreport')
pairs = [f'{c.get("name")}={c.get("value")}' for c in cookies
if c.get('name')
and any(d in (c.get('domain') or '') for d in ('meituan.com', 'dianping.com'))
and not any(s in (c.get('domain') or '') for s in skip)]
return '; '.join(pairs) if pairs else None
def _read_storage(page):
try:
raw = page.run_js('''
const dump = (store) => {
const data = {};
for (let i = 0; i < store.length; i++) {
const k = store.key(i);
const v = store.getItem(k);
if (v && v.length < 100000) data[k] = v;
}
return data;
};
return JSON.stringify({
localStorage: dump(window.localStorage),
sessionStorage: dump(window.sessionStorage),
});
''')
return json.loads(raw) if raw else {}
except Exception as e:
config.log(f'读取 storage 失败(不影响 Cookies):{e}', 'WARN')
return {}
def _save_login_state(page):
cookies = _cookies(page)
_ensure_dir(config.SESSIONS_DIR)
if cookies:
_atomic_write(config.COOKIE_FILE, json.dumps(cookies, ensure_ascii=False, indent=2))
config.log(f'已保存 {len(cookies)} 个 Cookies → {config.COOKIE_FILE}')
else:
config.log('未取到任何 Cookies(登录态可能未生效)', 'WARN')
header = _platform_cookie_header(cookies)
if header:
_atomic_write(config.COOKIE_HEADER_FILE, header)
storage = _read_storage(page)
ls, ss = (storage.get('localStorage') or {}), (storage.get('sessionStorage') or {})
_atomic_write(config.TOKEN_FILE, json.dumps({
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
'url': page.url,
'localStorage': ls,
'sessionStorage': ss,
}, ensure_ascii=False, indent=2))
domains = {}
for c in cookies:
d = c.get('domain') or '(空)'
domains[d] = domains.get(d, 0) + 1
summary = {
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
'url': page.url,
'title': (getattr(page, 'title', '') or ''),
'cookie_count': len(cookies),
'cookie_domains': domains,
'cookie_names': sorted({c.get('name') for c in cookies if c.get('name')}),
'storage_keys': {'localStorage': sorted(ls.keys()), 'sessionStorage': sorted(ss.keys())},
}
_atomic_write(config.META_FILE, json.dumps(summary, ensure_ascii=False, indent=2))
config.log(f'登录态已落盘:{len(cookies)} 个 Cookie,'
f'localStorage {len(ls)} 项 / sessionStorage {len(ss)} 项')
# ==================== 账号密码自动填写(可选) ====================
# 说明:只在「界面里配了账号 + 密码」时才动手;滑块/短信验证码、选商家仍交人工,
# 自动填写失败一律降级为原来的手工登录,不阻塞流程。
_TARGET_SELECTOR_JS = r'''
(function () {
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';
}
window.__xq41Visible = visible;
return 1;
})()
'''
_FILL_JS = r'''
(function () {
var USER = %(user)s, PWD = %(pwd)s;
var visible = window.__xq41Visible || function (el) {
if (!el || !el.getBoundingClientRect) return false;
var r = el.getBoundingClientRect();
return r.width > 2 && r.height > 2;
};
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 }));
el.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true, key: 'Enter' }));
}
// 密码框:优先 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);
var out = { ok: true, filled: !!(acc.value && pwd.value), filled_account: !!acc.value,
filled_pwd: !!pwd.value, agreement_found: false, checked_agreement: false,
reason: '' };
// ---------- 用户协议(不勾上就绝不点「登录」) ----------
// 实测 epassport: <input id="checkbox"> + <span class="ep-authorize">我已阅读并同意…>,
// 同一份协议在页面上渲染两遍、id 重复;勾选框也可能被自定义样式盖住,光标点不动。
function tipOf(el) {
var tip = el.getAttribute('aria-label') || '';
var scope = el.closest ? el.closest(
'.ep-protocol, .protocol, .agreement, .agree, [class*="protocol"], [class*="agreement"], [class*="agree"]'
) : null;
if (scope) tip += scope.textContent || '';
else if (el.parentElement && el.parentElement.parentElement) {
tip += el.parentElement.parentElement.textContent || '';
}
if (el.id) {
var lab = document.querySelector('label[for="' + el.id + '"]');
if (lab) tip += lab.textContent || '';
}
return tip;
}
function tryCheck(el) {
if (el.checked) return true;
// 真实页面结构:<input type="checkbox" id="checkbox"> 配 <label for="checkbox">
// 里放自定义方块 .checkbox_icon,input 本身常被样式盖住 —— 所以先走 label(用户真实点击路径),
// 再退到 input 自身、外层容器,最后强置 checked。
var fns = [
function () { var l = el.id && document.querySelector('label[for="' + el.id + '"]'); if (l) l.click(); },
function () { el.click(); },
function () {
var p = (el.closest && el.closest('.ep-checkbox-container, label, .checkbox')) || el.parentElement;
if (p) p.click();
},
function () { el.checked = true; el.dispatchEvent(new Event('change', { bubbles: true })); }
];
for (var i = 0; i < fns.length; i++) {
try { fns[i](); } catch (e) {}
if (el.checked) return true;
}
return !!el.checked;
}
var allBoxes = [].slice.call(document.querySelectorAll('input[type="checkbox"]')).filter(function (el) {
return !el.disabled;
});
var boxes = allBoxes.filter(visible);
// 协议框常被自定义样式盖住(opacity:0 / 尺寸 0),但它本身仍可点 —— 全被藏起来时退回全部
if (!boxes.length) boxes = allBoxes;
var agree = boxes.filter(function (el) {
var tip = tipOf(el);
if (/记住|自动登录|下次|保持登录/.test(tip)) return false;
return /同意|协议|隐私/.test(tip);
});
// 实测结构直接命中(.ep-protocol 容器 / id=checkbox),比文案猜测稳
var directAgree = allBoxes.filter(function (el) {
if (el.id === 'checkbox') return true;
return !!(el.closest && el.closest('.ep-protocol, .ep-protocol_container, [class*="protocol"]'));
})[0];
var agreeBox = directAgree || agree[0] || (boxes.length === 1 ? boxes[0] : null);
if (agreeBox) {
out.agreement_found = true;
out.checked_agreement = tryCheck(agreeBox);
if (!out.checked_agreement) out.reason = 'agreement-not-checked';
}
// 到此为止:只负责填账号密码 + 勾用户协议。
// 「登录」按钮、滑块 / 图形验证码、短信验证码一律不碰,全部留给用户自己操作。
return JSON.stringify(out);
})()
'''
_TAB_JS = r'''
(function () {
var visible = window.__xq41Visible || 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:
frame.run_js(_TARGET_SELECTOR_JS)
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。
# 以前只按字符串 json.loads,遇到 dict 会抛 TypeError → 明明填好了却判定"没填上"。
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 autofill_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, 'agreement_found': False, 'checked_agreement': False}
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
agree_ok = bool(fill.get('checked_agreement'))
agree_note = ',并已勾选用户协议' if agree_ok else ''
if fill.get('agreement_found') and not agree_ok:
config.log(f'已在 {where} 填好账号密码,但用户协议没能自动勾上:'
'请在浏览器里手动勾选协议后点「登录」', 'WARN')
show_login_notice(page, '请在浏览器里勾选「我已阅读并同意」后点「登录」',
'需要先勾选协议', frame=frame)
else:
config.log(f'已在 {where} 填好账号密码{agree_note},'
'请到浏览器窗口点「登录」(滑块 / 短信验证码也由你完成)')
show_login_notice(page, '请在浏览器窗口点「登录」',
'滑块 / 短信验证码按页面提示完成', frame=frame)
return True
time.sleep(config.AUTOFILL_POLL)
config.log(f'未找到账号密码输入框(等 {config.AUTOFILL_WAIT}s),请在浏览器窗口手动登录', 'WARN')
show_login_notice(page, '请在浏览器窗口手动登录经营宝',
'请手动输入账号密码')
return False
_CAPTCHA_JS = r'''
(function () {
var sels = ['iframe[src*="captcha"]', 'iframe[src*="gtimg"]', '.geetest_panel',
'.nc-container', '.nc_wrapper', '.yidun_popup', '.smc-captcha',
'.yoda-slider', '[id*="captcha"]'];
for (var i = 0; i < sels.length; i++) {
var el = document.querySelector(sels[i]);
if (!el) continue;
var r = el.getBoundingClientRect ? el.getBoundingClientRect() : null;
if (r && r.width > 10 && r.height > 10) return 1;
}
return 0;
})()
'''
def _has_captcha(page):
"""滑块/图形验证码是否可见(跨 iframe 一起看)。"""
for t in _targets(page):
try:
if str(t.run_js(_CAPTCHA_JS) or '') == '1':
return True
except Exception:
continue
return False
# 登录后的「选择商家版本」页探测(实测 DOM:main[data-v] > div.biz-item > .item-container + h2)
_BIZ_PROBE_JS = r'''
(function () {
var MARKS = %(marks)s;
var VISIBLE = function (el) {
if (!el || !el.getBoundingClientRect) return false;
var r = el.getBoundingClientRect();
return r.width > 2 && r.height > 2;
};
var cards = [].slice.call(document.querySelectorAll('.biz-item, [class*="biz-item"]'))
.filter(VISIBLE);
if (!cards.length) return JSON.stringify({ found: false });
var text = cards.map(function (el) {
return (el.textContent || '').replace(/\s+/g, '');
}).join('|');
var hit = 0;
MARKS.forEach(function (m) { if (text.indexOf(m) >= 0) hit++; });
return JSON.stringify({ found: hit >= 1, cards: cards.length, marks: hit });
})()
'''
# 点中目标商家版本:container=卡片内 .item-container,card=整卡,confirm=该页的「确定/下一步」
_BIZ_CLICK_JS = r'''
(function () {
var KEY = %(keyword)s, MODE = %(mode)s;
var VISIBLE = function (el) {
if (!el || !el.getBoundingClientRect) return false;
var r = el.getBoundingClientRect();
return r.width > 2 && r.height > 2;
};
var clicked = false;
if (MODE === 'confirm') {
var want = /^(确定|下一步|继续|确认|进入|进入后台)$/;
var btns = [].slice.call(document.querySelectorAll('button,a,div,span')).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'));
return !inner.some(function (c) { return want.test((c.textContent || '').replace(/\s+/g, '')); });
});
if (btns.length) { btns[0].click(); clicked = true; }
return JSON.stringify({ found: true, clicked: clicked, mode: MODE });
}
var cards = [].slice.call(document.querySelectorAll('.biz-item, [class*="biz-item"]'))
.filter(VISIBLE);
var marked = '我是' + KEY + '商家';
var hit = cards.filter(function (el) {
return (el.textContent || '').replace(/\s+/g, '').indexOf(marked) >= 0;
})[0] || cards.filter(function (el) {
return (el.textContent || '').indexOf(KEY) >= 0;
})[0];
if (!hit) return JSON.stringify({ found: false, clicked: false, mode: MODE });
var target = MODE === 'card' ? hit : (hit.querySelector('.item-container') || hit);
target.click();
return JSON.stringify({ found: true, clicked: true, mode: MODE });
})()
'''
def _biz_line_page(page):
"""当前页面是否为「选择商家版本」页(我是餐饮商家 / 我是非餐饮商家 两张卡)。"""
js = _BIZ_PROBE_JS % {'marks': json.dumps(list(config.BIZ_LINE_MARKERS), ensure_ascii=False)}
for t in _targets(page):
try:
raw = t.run_js(js)
info = json.loads(raw) if raw else None
if info and info.get('found'):
return True
except Exception:
continue
return False
def _click_biz_line(page, mode):
js = _BIZ_CLICK_JS % {'keyword': json.dumps(config.BIZ_LINE_KEYWORD, ensure_ascii=False),
'mode': json.dumps(mode)}
for t in _targets(page):
try:
raw = t.run_js(js)
info = json.loads(raw) if raw else None
if info and info.get('clicked'):
return info
except Exception:
continue
return {}
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
captcha_hint_at = captcha_checked_at = 0.0
biz_at, biz_tries, biz_gave_up = 0.0, 0, False
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')
# 「选择商家版本」页(我是餐饮商家 / 我是非餐饮商家):自动点「我是非餐饮商家」,
# 依次尝试「卡片容器 → 该页确定按钮 → 整卡」,最多 BIZ_LINE_MAX_TRIES 次
if time.time() - biz_at > config.BIZ_LINE_INTERVAL:
biz_at = time.time()
if _biz_line_page(page):
if biz_tries < config.BIZ_LINE_MAX_TRIES:
mode = ('container', 'confirm', 'card')[biz_tries]
r = _click_biz_line(page, mode)
biz_tries += 1
if r.get('clicked'):
config.log(f'已在「选择商家版本」页点选「我是'
f'{config.BIZ_LINE_KEYWORD}商家」({mode})')
time.sleep(config.POLL_SECONDS)
continue
elif not biz_gave_up:
biz_gave_up = True
config.log(f'「选择商家版本」页自动点选失败,请手动点「我是'
f'{config.BIZ_LINE_KEYWORD}商家」', 'WARN')
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
# 验证码提示:提交后常弹滑块/点选,最多每 10 秒探一次、每 60 秒提示一次
if state != 'other' and time.time() - captcha_checked_at > 10:
captcha_checked_at = time.time()
if _has_captcha(page) and time.time() - captcha_hint_at > 60:
captcha_hint_at = time.time()
config.log('检测到滑块/图形验证码,请在浏览器窗口手动完成(完成后自动继续)')
show_login_notice(page, '请完成滑块 / 图形验证码',
'拖动滑块或点选完成验证')
time.sleep(config.POLL_SECONDS)
return False
def ensure_login(page, username='', password=''):
"""确保 page 已进入商家后台;必要时用配置的账号密码自动登录,失败则等人工。"""
config.log(f'打开经营宝:{config.HOME_URL}')
page.get(config.HOME_URL)
time.sleep(config.POLL_SECONDS)
# 复用一个短窗口:profile 里残留会话能直接进后台就不用打扰
reuse_end = time.time() + config.BACKEND_STABLE + 10
while time.time() < reuse_end:
state = classify(page.url)
if state == 'backend':
time.sleep(config.SETTLE_WAIT)
_save_login_state(page)
hide_login_notice(page)
return True, '复用缓存登录态'
if state in ('login', 'biz_choice'):
break
time.sleep(config.POLL_SECONDS)
username = (username or '').strip()
password = (password or '').strip()
if username and password:
if classify(page.url) == 'biz_choice':
config.log('账号已登录,仅需选择商家(不需要再填账号密码)')
else:
config.log('检测到未登录:自动填好账号密码 + 勾选用户协议,'
'「登录」按钮与验证码留给你在浏览器里操作…')
autofill_login(page, username, password)
elif username or password:
config.log('账号 / 密码只填了一项,本次跳过自动登录,请手工登录', 'WARN')
config.log(f'等待进入商家后台,最多 {config.LOGIN_WAIT} 秒'
f'(滑块验证码 / 选商家需在浏览器窗口人工完成)…')
if not _wait_backend(page):
cookies = _cookies(page)
config.log('当前 Cookie:' + ', '.join(sorted({c.get('name') for c in cookies if c.get('name')})),
'WARN')
return False, '登录超时(未进入商家后台)'
time.sleep(config.SETTLE_WAIT)
if classify(page.url) != 'backend':
return False, '登录态未稳定(落盘前离开后台)'
_save_login_state(page)
hide_login_notice(page)
return True, '登录成功'