# -*- coding: utf-8 -*- """xq0079 人工登录通道:弹可见浏览器 + 预填账号密码,验证码由人工输入并点「登录」。 为什么需要这条通道: 接口登录依赖 ddddocr 识别图形验证码(4 位字母数字),识别率不是 100%, 每次提交都计入平台失败次数(服务端对「验证码错」和「账号密码错」都回 1003, 连续失败有锁号风险)。人工登录不自动提交表单,只做预填,验证码由人看, 一次就能过,且不消耗插件的重试轮次。 实现要点(登录页 DOM 来自实际页面): 账号 input#loginAcc(placeholder「请输入商户编号/门店编号/手机号」) 密码 input#loginPwd(ant-input-password 内) 验证码 input#imageCode + 右侧 登录按钮 button.ant-btn-primary(文案「登 录」) 登录成功后前端会整页跳转,并把用户信息(含 token)写入 sessionStorage.user, 这里轮询 sessionStorage 取 token——比抓 cookie 稳,天阙业务接口靠 token 头鉴权。 风控相关(多账号必须看): - 浏览器用户目录按账号隔离(config.get_profile_dir),不共用 DrissionPage 默认的 %TEMP%\\DrissionPage\\userData 公共目录,避免两个账号串 cookie / 登录态; - 同一账号每次都用同一个 profile:cookie 保留、指纹稳定,表现接近真人固定浏览器; - 每个实例用独立调试端口,避免与其它插件或已开浏览器抢 9222; - 账号之间由调用方随机停顿几秒再登(config.ACCOUNT_GAP_SECONDS),不并发、 不秒连,减少「同设备短时多账号」这类风控特征; - 登录完成后只关窗口,不清 profile(清了下一次又像一台新设备,反而更可疑)。 """ import json import socket import time from .. import config def _log(msg, level="INFO"): config.log(msg, level) def _free_port(): """取一个空闲本地端口,避免与其它插件/已开浏览器抢同一个调试端口。""" with socket.socket() as s: s.bind(("127.0.0.1", 0)) return s.getsockname()[1] def _new_page(account): """按账号隔离浏览器用户目录(profile)后开窗。 DrissionPage 默认把 profile 放 %TEMP%\\DrissionPage\\userData\\<端口>, 是所有插件共用的同一个配置目录——不同账号/不同插件会串 cookie 与登录态。 这里按账号 md5 建独立目录:同账号每次复用(cookie 保留、指纹稳定,像真人固定浏览器), 不同账号之间完全隔离;账号间再随机停顿几秒,避免同一秒连登被风控盯上。 """ from DrissionPage import ChromiumOptions, ChromiumPage profile = config.get_profile_dir(account) opts = ChromiumOptions() opts.set_user_data_path(profile) # 账号级隔离(也避开 %TEMP% 公共目录) opts.set_local_port(_free_port()) # 独立端口,防与其他实例冲突 opts.set_argument("--start-maximized") return ChromiumPage(opts), profile def _alive(page): try: return bool(page.states.is_alive) except Exception: return False def _js(page, script, times=5, gap=0.5): """页面跳转瞬间 run_js 会抛 ContextLostError,重试几次。""" for _ in range(times): try: return page.run_js(script) except Exception: time.sleep(gap) return None def _wait_form(page, timeout=40): """等登录表单渲染完成(umi 首屏是 JS 渲染,input 出现才算就绪)。""" for _ in range(timeout): n = _js(page, "return document.querySelectorAll('input').length", times=2) or 0 if n >= 3: return True time.sleep(1) return False def _fill(page, account, password): """预填账号密码(人工只需输验证码)。字段缺失不影响人工操作。""" try: acc = page.ele('#loginAcc', timeout=5) or page.ele('css:input[placeholder*="商户编号"]', timeout=3) if acc: acc.clear() acc.input(account) except Exception as exc: _log(f"预填账号失败(可手动输入):{exc}", "WARN") if not password: return try: pwd = page.ele('#loginPwd', timeout=5) or page.ele('css:input[type="password"]', timeout=3) if pwd: pwd.clear() pwd.input(password) except Exception as exc: _log(f"预填密码失败(可手动输入):{exc}", "WARN") def _read_user(page): """读 sessionStorage.user(登录成功后前端写入,含 token)。""" raw = _js(page, "return sessionStorage.getItem('user')", times=2) if not raw: return None try: user = json.loads(raw) except ValueError: return None if isinstance(user, dict) and user.get("token"): return user return None def manual_login(account, password, wait_seconds=None): """人工登录:返回 {success, token, user, message}。 不开无头窗口:人工要看验证码。登录成功后关闭浏览器(token 已拿到,不需要常驻)。 """ wait_seconds = wait_seconds or config.MANUAL_LOGIN_WAIT page = None try: page, profile = _new_page(account) _log(f"浏览器用户目录(该账号专用):{profile}", "DEBUG") page.get(config.BASE_URL + config.LOGIN_PAGE) time.sleep(2) if not _wait_form(page, timeout=15): # 这个 profile 上次登录后 cookie 还在,可能直接进了后台 user = _read_user(page) if user: token = str(user.get("token") or "") merchant = str(user.get("merchantName") or user.get("userName") or account) _log(f"该账号浏览器里仍是登录态,直接复用:{merchant}") return {"success": True, "token": token, "user": user, "message": "浏览器已有登录态", "merchant": merchant} _log("登录页未出现表单(疑似残留登录态),清理该账号浏览器缓存后重试", "WARN") try: page.clear_cache() except Exception as exc: _log(f"清理浏览器缓存失败(可手动清理):{exc}", "WARN") page.get(config.BASE_URL + config.LOGIN_PAGE) time.sleep(2) if not _wait_form(page, timeout=30): return {"success": False, "token": "", "user": {}, "message": "登录页 40 秒未渲染完成(网络异常或平台改版)"} _fill(page, account, password) _log(f"已打开登录页并预填账号 {account}(密码仅本地预填,可自行修改)") _log(f"请在浏览器里输入图形验证码并点「登 录」,插件会等待 {wait_seconds} 秒…") _log("提示:本方式不自动提交表单,不会消耗接口登录的重试轮次") deadline = time.time() + wait_seconds next_tip = time.time() + config.MANUAL_TIP_SECONDS while time.time() < deadline: if not _alive(page): return {"success": False, "token": "", "user": {}, "message": "浏览器被关闭,人工登录已取消"} user = _read_user(page) if user: token = str(user.get("token") or "") merchant = str(user.get("merchantName") or user.get("userName") or account) _log(f"人工登录成功:{merchant}(token {token[:12]}…)") return {"success": True, "token": token, "user": user, "message": "人工登录成功", "merchant": merchant} if time.time() >= next_tip: _log(f"仍在等待人工登录,剩余 {int(deadline - time.time())} 秒…") next_tip = time.time() + config.MANUAL_TIP_SECONDS time.sleep(config.MANUAL_POLL_SECONDS) return {"success": False, "token": "", "user": {}, "message": f"人工登录等待超时({wait_seconds} 秒),未检测到登录成功"} except Exception as exc: return {"success": False, "token": "", "user": {}, "message": f"人工登录异常:{exc}"} finally: # 只关窗口,保留该账号的 profile(cookie / 指纹延续,下次打开像本人浏览器) if page is not None: try: page.quit() except Exception: pass