579 lines
24 KiB
Python
579 lines
24 KiB
Python
# -*- 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) {
|
||
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_account: !!acc.value, filled_pwd: !!pwd.value,
|
||
checked_agreement: false, submitted: false };
|
||
|
||
// 协议复选框(实测 epassport: <input id="checkbox"> + <span class="ep-authorize">我已阅读并同意…>,
|
||
// 页面上同一份协议渲染了两遍、id 重复):只点「够得着同意/协议/隐私文案」且未勾选的第一项,
|
||
// 避免点到「记住密码/自动登录」这类反向开关,也避免重复点击把同一状态点回去
|
||
var boxes = [].slice.call(document.querySelectorAll('input[type="checkbox"]')).filter(function (el) {
|
||
return visible(el) && !el.checked && !el.disabled;
|
||
});
|
||
var agree = boxes.filter(function (el) {
|
||
var tip = el.getAttribute('aria-label') || '';
|
||
var scope = el.closest ? el.closest('.ep-protocol, .protocol, .agreement, .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 || '';
|
||
}
|
||
if (/记住|自动登录|下次|保持登录/.test(tip)) return false;
|
||
return /同意|协议|隐私/.test(tip);
|
||
});
|
||
if (agree.length) {
|
||
try { agree[0].click(); out.checked_agreement = true; } catch (e) {}
|
||
} else if (boxes.length === 1) {
|
||
try { boxes[0].click(); out.checked_agreement = true; } catch (e) {}
|
||
}
|
||
|
||
// 登录按钮:先试实测结构(form.ep-password-login_container button[type=submit] / button.ep-login_btn),
|
||
// 找不到再退化为「文本恰为 登录/立即登录 的最内层元素」
|
||
var texts = /^(登录|立即登录|账号登录|登入)$/;
|
||
var btn = document.querySelector(
|
||
'form.ep-password-login_container button[type="submit"], button.ep-login_btn'
|
||
);
|
||
if (btn && !visible(btn)) btn = null;
|
||
if (!btn) {
|
||
var nodes = [].slice.call(document.querySelectorAll('button,a,span,div,input[type="submit"]'));
|
||
var hit = nodes.filter(function (el) {
|
||
if (!visible(el)) return false;
|
||
if (el.tagName === 'INPUT') return /^登\s*录$/.test((el.value || '').trim());
|
||
if (!texts.test((el.textContent || '').replace(/\s+/g, ''))) return false;
|
||
var inner = [].slice.call(el.querySelectorAll('button,a,span,div'));
|
||
return !inner.some(function (c) { return texts.test((c.textContent || '').replace(/\s+/g, '')); });
|
||
});
|
||
btn = hit[0] || null;
|
||
}
|
||
if (btn) { btn.click(); out.submitted = true; }
|
||
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';
|
||
})()
|
||
'''
|
||
|
||
|
||
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)})
|
||
return json.loads(raw) if raw else None
|
||
except Exception as e:
|
||
config.log(f'自动填写尝试异常:{e}', 'DEBUG')
|
||
return None
|
||
|
||
|
||
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):
|
||
info = _fill_once(frame, username, password)
|
||
if info and info.get('ok'):
|
||
try:
|
||
where = (getattr(frame, 'url', '') or '').split('?')[0] or '主页面'
|
||
except Exception:
|
||
where = '主页面'
|
||
if not info.get('submitted'):
|
||
config.log(f'已在 {where} 填写账号密码,但没找到「登录」按钮,请手动点一下', 'WARN')
|
||
else:
|
||
config.log(f'已在 {where} 自动填写账号密码并提交登录'
|
||
'(若弹出滑块/短信验证码,请在浏览器窗口手动完成)')
|
||
return True
|
||
if info and info.get('reason') == 'no-password' and not tab_clicked:
|
||
if _switch_account_tab(frame):
|
||
tab_clicked = True
|
||
config.log('登录页默认非账密方式,已切换到「账号登录」', 'DEBUG')
|
||
time.sleep(config.AUTOFILL_POLL)
|
||
time.sleep(config.AUTOFILL_POLL)
|
||
config.log(f'未找到账号密码输入框(等 {config.AUTOFILL_WAIT}s),请在浏览器窗口手动登录', 'WARN')
|
||
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
|
||
|
||
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('请在浏览器窗口内完成登录(账号密码 / 短信验证码 / 扫码均可)')
|
||
elif state == 'biz_choice' and time.time() - biz_hint_at > 30:
|
||
biz_hint_at = time.time()
|
||
config.log('账号已登录,请在页面上选择要进入的商家(脚本不自动选,避免进错店)')
|
||
|
||
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:
|
||
return True
|
||
else:
|
||
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('检测到滑块/图形验证码,请在浏览器窗口手动完成'
|
||
'(完成后脚本自动继续)')
|
||
|
||
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)
|
||
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)
|
||
time.sleep(config.AUTOFILL_SUBMIT_DELAY)
|
||
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)
|
||
return True, '登录成功'
|