Files
37duAutomation/plugins/xq0041/data/meituan_login.py
T

200 lines
7.5 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/票据。
为什么不用 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)} 项')
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
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('请在浏览器窗口内完成登录(账号密码 / 短信验证码 / 扫码均可)')
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
time.sleep(config.POLL_SECONDS)
return False
def ensure_login(page):
"""确保 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)
config.log(f'需要人工登录,最多等待 {config.LOGIN_WAIT} 秒…')
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, '登录成功'