Files
37duAutomation/plugins/XQ0001-0100/XQ0042 抖音平台核对/data/douyin_login.py
T

381 lines
14 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/票据。
实测链路(2026-10-28):
https://life.douyin.com/p/login 登录页(账密 / 短信验证码 / 扫码)
sso.douyin.com / passport.douyin.com
登录成功后跳 https://life.douyin.com/p/home?groupid=...,期间可能短暂回跳登录页
判定规则(三条同时满足):
1) 当前 URL 是 life.douyin.com 的非登录页;
2) douyin 域下存在会话票据 Cookie(sessionid* / sid_tt* / sid_guard*);
3) 连续稳定 BACKEND_STABLE 秒,期间没有被踢回登录页。
登录态缓存(跨次复用):
来客票据 sessionid_ls / sid_tt_ls / sid_guard_ls 都是**会话级 Cookie**,Chromium 退出后
并不保证落盘保留(只靠 profile 目录不可靠),所以每次运行前把快照 douyin_cookies.json
重新注入新启动的浏览器(page.set.cookies),profile 只当兜底;注入后仍进不了后台才转人工登录。
落盘(%LOCALAPPDATA%\\37duAutomation\\.sessions\\douyin_*):
douyin_cookies.json / douyin_cookies_header.txt / douyin_tokens.json / douyin_session_meta.json
"""
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 _host(url):
try:
return (url or '').split('://', 1)[-1].split('/', 1)[0].split('?', 1)[0].lower()
except Exception:
return ''
def classify(url):
"""页面状态:login(登录页/统一登录域)/ backend(来客后台)/ other。"""
low = (url or '').strip().lower()
if not low.startswith('http'):
return 'other'
if any(h in low for h in config.PASSPORT_HINTS):
return 'login'
host = _host(low)
if host.endswith(config.BACKEND_HOST):
path = low.split(host, 1)[-1]
if any(p in path for p in config.LOGIN_PAGE_HINTS):
return 'login'
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 _has_session_cookie(cookies):
"""douyin 域下是否存在登录票据 Cookie(名字带 _ls 等分区后缀,按前缀匹配)。"""
for c in cookies:
name = (c.get('name') or '').strip().lower()
if name.startswith(config.SESSION_COOKIE_PREFIXES) and c.get('value') \
and 'douyin.com' in (c.get('domain') or ''):
return True
return False
def _ticket_cookies(cookies):
out = []
for c in cookies:
name = (c.get('name') or '').strip()
low = name.lower()
if not name or not c.get('value'):
continue
if any(k in low for k in config.IGNORE_KEY_HINTS):
continue
if any(k in low for k in config.TICKET_KEY_HINTS):
out.append(name)
return sorted(set(out))
def _cookie_header(cookies):
"""按浏览器原始顺序拼出 douyin 域 Cookie 头(passport/埋点域名不要)。"""
skip = ('passport', 'sso', 'report', 'monitor', 'lx', 'dreport', 'open.douyin')
pairs = [f'{c.get("name")}={c.get("value")}' for c in cookies
if c.get('name')
and 'douyin.com' in (c.get('domain') or '')
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 = _cookie_header(cookies)
if header:
_atomic_write(config.COOKIE_HEADER_FILE, header)
config.log(f'已保存 douyin 域 Cookie 头({header.count(";") + 1} 项)')
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,
'has_session_cookie': _has_session_cookie(cookies),
'ticket_cookies': _ticket_cookies(cookies),
'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)} 项')
return summary
# ==================== 登录态缓存:快照 → 浏览器注入 ====================
# 只注入 douyin 相关域;埋点/上报域(report/monitor/lx/dreport)丢掉,减少无关 Cookie 干扰。
_INJECT_SKIP_DOMAINS = ('report', 'monitor', 'lx', 'dreport', 'open.douyin')
def _load_cookies():
"""读取落盘 Cookies 快照:去掉空值与已过期的,返回列表;无可用项返回 None。"""
path = config.COOKIE_FILE
if not os.path.exists(path):
return None
try:
with open(path, encoding='utf-8') as f:
cookies = json.load(f)
except Exception as e:
config.log(f'读取 Cookies 快照失败(忽略缓存):{e}', 'WARN')
return None
now = time.time()
alive = []
for c in cookies or []:
if not c.get('name') or not c.get('value'):
continue
try:
exp = float(c.get('expires'))
except (TypeError, ValueError):
exp = -1.0
if exp > 0 and exp <= now: # 已过期:注入了也只会被服务端判无效
continue
alive.append(c)
return alive or None
def _inject_item(c):
"""快照里的 Cookie → page.set.cookies 需要的结构(只带有效字段)。"""
item = {
'name': c.get('name'),
'value': c.get('value'),
'domain': c.get('domain') or config.BACKEND_HOST,
'path': c.get('path') or '/',
}
try:
exp = float(c.get('expires'))
except (TypeError, ValueError):
exp = -1.0
if exp > 0:
item['expires'] = exp # 会话级 Cookie(-1)不传 expires,交给浏览器当会话 Cookie
if c.get('secure'):
item['secure'] = True
if c.get('httpOnly'):
item['httpOnly'] = True
same_site = str(c.get('sameSite') or '').strip()
if same_site in ('Strict', 'Lax', 'None'):
item['sameSite'] = same_site
return item
def restore_cookies(page):
"""把上次落盘的登录态注入刚启动的浏览器,返回注入条数(0=无可用缓存)。"""
cookies = _load_cookies()
if not cookies:
config.log('无可用登录态快照(首次运行或已过期)', 'DEBUG')
return 0
items = [_inject_item(c) for c in cookies
if 'douyin.com' in (c.get('domain') or '')
and not any(s in (c.get('domain') or '') for s in _INJECT_SKIP_DOMAINS)]
if not items:
return 0
injected = False
try:
# 浏览器级注入(Storage.setCookies):此时页面还是 about:blank,不依赖加载完成
page.browser.set.cookies(items)
injected = True
except Exception as e:
config.log(f'浏览器级注入失败,改走标签页注入:{e}', 'DEBUG')
if not injected:
try:
page.set.cookies(items)
injected = True
except Exception as e:
config.log(f'注入缓存 Cookies 失败(改走 profile / 人工登录):{e}', 'WARN')
return 0
saved_at = ''
try:
with open(config.META_FILE, encoding='utf-8') as f:
saved_at = str((json.load(f) or {}).get('saved_at') or '')
except Exception:
pass
config.log(f'已注入缓存登录态:{len(items)} 个 douyin Cookie'
+ (f'(快照时间 {saved_at})' if saved_at else '')
+ f',含会话票据={"是" if _has_session_cookie(items) else "否"}')
return len(items)
def clear_snapshot():
"""删除登录态快照文件(强制重新登录时用,避免下次又被旧账号缓存带进去)。"""
for path in (config.COOKIE_FILE, config.COOKIE_HEADER_FILE,
config.TOKEN_FILE, config.META_FILE):
try:
if os.path.exists(path):
os.remove(path)
except Exception as e:
config.log(f'删除登录态快照失败(忽略):{path} {e}', 'WARN')
def clear_browser_cookies(page):
"""清掉浏览器里的 Cookies(localStorage 保留,不影响页面偏好配置)。"""
if page is None:
return
try:
page.clear_cache(session_storage=False, local_storage=False, cache=False, cookies=True)
return
except Exception as e:
config.log(f'清除浏览器 Cookies 失败(改走 CDP):{e}', 'DEBUG')
try:
page.set.cookies.clear() # Network.clearBrowserCookies
except Exception as e:
config.log(f'清除浏览器 Cookies 失败:{e}', 'WARN')
def _wait_backend(page):
"""等人工完成「登录 + 验证码」,返回 True/False。"""
deadline = time.time() + config.LOGIN_WAIT
last_url, last_state = None, None
backend_since = None
login_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('请在浏览器窗口内完成登录'
'(账号密码 / 短信验证码 / 扫码 / 滑块均可,脚本不碰表单)')
if state == 'backend' and _has_session_cookie(_cookies(page)):
if backend_since is None:
backend_since = time.time()
config.log(f'已进来客后台且票据已种下,等待 {config.BACKEND_STABLE}s '
f'确认不会再被踢回登录页…')
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, force=False):
"""确保 page 已进入来客后台;必要时停在前台等人工登录。
复用顺序:落盘快照注入(restore_cookies)→ profile 残留会话 → 人工登录。
force=True 先清空浏览器 Cookies 与本地快照,再等人工重新登录(换账号/排查问题用)。
"""
if force:
config.log('强制重新登录:清除浏览器 Cookies 与本地登录态快照', 'WARN')
clear_browser_cookies(page)
clear_snapshot()
else:
restore_cookies(page)
config.log(f'打开抖音来客:{config.HOME_URL}')
page.get(config.HOME_URL)
time.sleep(config.POLL_SECONDS)
# 复用缓存(注入的 Cookie + profile 残留):能直接进后台就不用打扰用户
if not force:
reuse_end = time.time() + config.BACKEND_STABLE + 10
while time.time() < reuse_end:
state = classify(page.url)
if state == 'backend' and _has_session_cookie(_cookies(page)):
config.log(f'缓存登录态有效,直接复用(URL={page.url})')
time.sleep(config.SETTLE_WAIT)
_save_login_state(page)
return True, '复用缓存登录态'
if state == 'login':
break
time.sleep(config.POLL_SECONDS)
config.log('缓存登录态已失效,转人工登录', 'WARN')
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, '登录成功'