base.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. # -*- coding: utf-8 -*-
  2. """
  3. 平台发布基类
  4. 提供通用的发布接口和工具方法
  5. """
  6. import asyncio
  7. import json
  8. import os
  9. import uuid
  10. import random
  11. from abc import ABC, abstractmethod
  12. from dataclasses import dataclass, field
  13. from datetime import datetime
  14. from typing import List, Optional, Callable, Dict, Any
  15. from playwright.async_api import async_playwright, Browser, BrowserContext, Page
  16. # 导入反检测工具
  17. try:
  18. from utils.stealth import (
  19. get_browser_context_args,
  20. get_all_stealth_scripts,
  21. get_user_agent,
  22. get_viewport,
  23. )
  24. STEALTH_AVAILABLE = True
  25. except ImportError:
  26. STEALTH_AVAILABLE = False
  27. print("[Warning] Stealth utils not available, anti-detection disabled")
  28. @dataclass
  29. class PublishParams:
  30. """发布参数"""
  31. title: str
  32. video_path: str
  33. description: str = ""
  34. cover_path: Optional[str] = None
  35. tags: List[str] = field(default_factory=list)
  36. publish_date: Optional[datetime] = None
  37. location: str = "重庆市"
  38. def __post_init__(self):
  39. if not self.description:
  40. self.description = self.title
  41. @dataclass
  42. class PublishResult:
  43. """发布结果"""
  44. success: bool
  45. platform: str
  46. video_id: str = ""
  47. video_url: str = ""
  48. message: str = ""
  49. error: str = ""
  50. need_captcha: bool = False
  51. captcha_type: str = ""
  52. screenshot_base64: str = ""
  53. page_url: str = ""
  54. status: str = ""
  55. screenshot_path: str = ""
  56. @dataclass
  57. class WorkItem:
  58. """作品数据"""
  59. work_id: str
  60. title: str
  61. cover_url: str = ""
  62. video_url: str = ""
  63. duration: int = 0 # 秒
  64. status: str = "published" # published, reviewing, rejected, draft
  65. publish_time: str = ""
  66. play_count: int = 0
  67. like_count: int = 0
  68. comment_count: int = 0
  69. share_count: int = 0
  70. collect_count: int = 0
  71. def to_dict(self) -> Dict[str, Any]:
  72. return {
  73. "work_id": self.work_id,
  74. "title": self.title,
  75. "cover_url": self.cover_url,
  76. "video_url": self.video_url,
  77. "duration": self.duration,
  78. "status": self.status,
  79. "publish_time": self.publish_time,
  80. "play_count": self.play_count,
  81. "like_count": self.like_count,
  82. "comment_count": self.comment_count,
  83. "share_count": self.share_count,
  84. "collect_count": self.collect_count,
  85. }
  86. @dataclass
  87. class CommentItem:
  88. """评论数据"""
  89. comment_id: str
  90. parent_comment_id: str
  91. work_id: str
  92. content: str
  93. author_id: str = ""
  94. author_name: str = ""
  95. author_avatar: str = ""
  96. like_count: int = 0
  97. reply_count: int = 0
  98. create_time: str = ""
  99. is_author: bool = False # 是否是作者的评论
  100. replies: List["CommentItem"] = field(default_factory=list)
  101. def to_dict(self) -> Dict[str, Any]:
  102. return {
  103. "comment_id": self.comment_id,
  104. "parent_comment_id": self.parent_comment_id,
  105. "work_id": self.work_id,
  106. "content": self.content,
  107. "author_id": self.author_id,
  108. "author_name": self.author_name,
  109. "author_avatar": self.author_avatar,
  110. "like_count": self.like_count,
  111. "reply_count": self.reply_count,
  112. "create_time": self.create_time,
  113. "is_author": self.is_author,
  114. "replies": [r.to_dict() for r in self.replies],
  115. }
  116. @dataclass
  117. class WorksResult:
  118. """作品列表结果"""
  119. success: bool
  120. platform: str
  121. works: List[WorkItem] = field(default_factory=list)
  122. total: int = 0
  123. has_more: bool = False
  124. next_page: Any = ""
  125. error: str = ""
  126. debug_info: str = "" # 调试信息
  127. def to_dict(self) -> Dict[str, Any]:
  128. return {
  129. "success": self.success,
  130. "platform": self.platform,
  131. "works": [w.to_dict() for w in self.works],
  132. "total": self.total,
  133. "has_more": self.has_more,
  134. "next_page": self.next_page,
  135. "error": self.error,
  136. "debug_info": self.debug_info,
  137. }
  138. @dataclass
  139. class CommentsResult:
  140. """评论列表结果"""
  141. success: bool
  142. platform: str
  143. work_id: str
  144. comments: List[CommentItem] = field(default_factory=list)
  145. total: int = 0
  146. has_more: bool = False
  147. error: str = ""
  148. def to_dict(self) -> Dict[str, Any]:
  149. return {
  150. "success": self.success,
  151. "platform": self.platform,
  152. "work_id": self.work_id,
  153. "comments": [c.to_dict() for c in self.comments],
  154. "total": self.total,
  155. "has_more": self.has_more,
  156. "error": self.error,
  157. }
  158. class BasePublisher(ABC):
  159. """
  160. 平台发布基类
  161. 所有平台发布器都需要继承此类
  162. """
  163. platform_name: str = "base"
  164. login_url: str = ""
  165. publish_url: str = ""
  166. cookie_domain: str = ""
  167. def __init__(self, headless: bool = True):
  168. self.headless = headless
  169. self.browser: Optional[Browser] = None
  170. self.context: Optional[BrowserContext] = None
  171. self.page: Optional[Page] = None
  172. self.on_progress: Optional[Callable[[int, str], None]] = None
  173. self.user_id: Optional[int] = None
  174. self.publish_task_id: Optional[int] = None
  175. self.publish_account_id: Optional[int] = None
  176. self.proxy_config: Optional[Dict[str, Any]] = None
  177. def set_progress_callback(self, callback: Callable[[int, str], None]):
  178. """设置进度回调"""
  179. self.on_progress = callback
  180. def report_progress(self, progress: int, message: str):
  181. """报告进度"""
  182. print(f"[{self.platform_name}] [{progress}%] {message}")
  183. if self.on_progress:
  184. self.on_progress(progress, message)
  185. @staticmethod
  186. def parse_cookies(cookies_str: str) -> list:
  187. """解析 cookie 字符串为列表"""
  188. try:
  189. cookies = json.loads(cookies_str)
  190. if isinstance(cookies, list):
  191. return cookies
  192. except json.JSONDecodeError:
  193. pass
  194. # 字符串格式: name=value; name2=value2
  195. cookies = []
  196. for item in cookies_str.split(";"):
  197. item = item.strip()
  198. if "=" in item:
  199. name, value = item.split("=", 1)
  200. cookies.append(
  201. {
  202. "name": name.strip(),
  203. "value": value.strip(),
  204. "domain": "",
  205. "path": "/",
  206. }
  207. )
  208. return cookies
  209. @staticmethod
  210. def _normalize_same_site(value: Any) -> Optional[str]:
  211. """将不同来源的 sameSite 值转换为 Playwright 接受的值。"""
  212. if value is None:
  213. return None
  214. v = str(value).strip().lower()
  215. if not v:
  216. return None
  217. mapping = {
  218. "strict": "Strict",
  219. "lax": "Lax",
  220. "none": "None",
  221. "no_restriction": "None", # Electron
  222. "unspecified": None, # Electron: 不传该字段
  223. }
  224. return mapping.get(v, None)
  225. @classmethod
  226. def _sanitize_cookie_for_playwright(
  227. cls, cookie: Dict[str, Any], default_domain: str
  228. ) -> Optional[Dict[str, Any]]:
  229. """清洗 cookie 字段,避免 BrowserContext.add_cookies 参数校验失败。"""
  230. if not isinstance(cookie, dict):
  231. return None
  232. name = str(cookie.get("name") or "").strip()
  233. if not name:
  234. return None
  235. cleaned: Dict[str, Any] = {
  236. "name": name,
  237. "value": str(cookie.get("value") or ""),
  238. }
  239. url = str(cookie.get("url") or "").strip()
  240. if url:
  241. cleaned["url"] = url
  242. else:
  243. domain = str(cookie.get("domain") or "").strip() or default_domain
  244. if not domain:
  245. return None
  246. cleaned["domain"] = domain
  247. cleaned["path"] = str(cookie.get("path") or "/")
  248. if "httpOnly" in cookie:
  249. cleaned["httpOnly"] = bool(cookie.get("httpOnly"))
  250. if "secure" in cookie:
  251. cleaned["secure"] = bool(cookie.get("secure"))
  252. expires_raw = cookie.get("expires", cookie.get("expirationDate"))
  253. if expires_raw not in (None, "", 0):
  254. try:
  255. expires_val = float(expires_raw)
  256. if expires_val > 0:
  257. cleaned["expires"] = expires_val
  258. except Exception:
  259. pass
  260. same_site = cls._normalize_same_site(
  261. cookie.get("sameSite", cookie.get("same_site"))
  262. )
  263. if same_site:
  264. cleaned["sameSite"] = same_site
  265. return cleaned
  266. @staticmethod
  267. def cookies_to_string(cookies: list) -> str:
  268. """将 cookie 列表转换为字符串"""
  269. return "; ".join([f"{c['name']}={c['value']}" for c in cookies])
  270. async def init_browser(
  271. self, storage_state: str = None, proxy_config: Dict[str, Any] = None
  272. ):
  273. """初始化浏览器(带反检测增强)"""
  274. print(
  275. f"[{self.platform_name}] init_browser: headless={self.headless}", flush=True
  276. )
  277. playwright = await async_playwright().start()
  278. proxy = proxy_config or self.proxy_config
  279. has_proxy = proxy and isinstance(proxy, dict) and proxy.get("server")
  280. if has_proxy:
  281. print(f"[{self.platform_name}] 使用代理: {proxy.get('server')}", flush=True)
  282. # 浏览器启动参数
  283. launch_args = {
  284. "headless": self.headless,
  285. "args": [
  286. "--disable-blink-features=AutomationControlled",
  287. "--disable-features=IsolateOrigins,site-per-process",
  288. "--disable-site-isolation-trials",
  289. "--no-sandbox",
  290. "--disable-setuid-sandbox",
  291. "--disable-dev-shm-usage",
  292. "--disable-web-security",
  293. "--disable-features=VizDisplayCompositor",
  294. "--disable-infobars",
  295. "--disable-extensions",
  296. "--disable-gpu",
  297. "--window-size=1920,1080",
  298. ],
  299. }
  300. if has_proxy:
  301. launch_args["proxy"] = proxy
  302. self.browser = await playwright.chromium.launch(**launch_args)
  303. # 生成浏览器上下文参数(带反检测配置)
  304. if STEALTH_AVAILABLE:
  305. context_args = get_browser_context_args(
  306. proxy_config=proxy if has_proxy else None
  307. )
  308. # 确保不使用代理参数(代理在 launch 时已设置)
  309. if "proxy" in context_args:
  310. del context_args["proxy"]
  311. else:
  312. context_args = {
  313. "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
  314. "viewport": {"width": 1920, "height": 1080},
  315. "locale": "zh-CN",
  316. "timezone_id": "Asia/Shanghai",
  317. }
  318. if storage_state and os.path.exists(storage_state):
  319. context_args["storage_state"] = storage_state
  320. self.context = await self.browser.new_context(**context_args)
  321. # 注入反检测脚本
  322. if STEALTH_AVAILABLE:
  323. stealth_script = get_all_stealth_scripts()
  324. await self.context.add_init_script(stealth_script)
  325. print(f"[{self.platform_name}] 已注入反检测脚本", flush=True)
  326. self.page = await self.context.new_page()
  327. # 设置额外的页面属性
  328. await self.page.set_extra_http_headers(
  329. {
  330. "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
  331. "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
  332. "Accept-Encoding": "gzip, deflate, br",
  333. "Connection": "keep-alive",
  334. "Upgrade-Insecure-Requests": "1",
  335. "Sec-Fetch-Dest": "document",
  336. "Sec-Fetch-Mode": "navigate",
  337. "Sec-Fetch-Site": "none",
  338. "Sec-Fetch-User": "?1",
  339. "Cache-Control": "max-age=0",
  340. }
  341. )
  342. print(
  343. f"[{self.platform_name}] 浏览器初始化完成 (stealth={'enabled' if STEALTH_AVAILABLE else 'disabled'})",
  344. flush=True,
  345. )
  346. return self.page
  347. async def set_cookies(self, cookies: list):
  348. """设置 cookies"""
  349. if not self.context:
  350. raise Exception("Browser context not initialized")
  351. sanitized: List[Dict[str, Any]] = []
  352. for cookie in cookies:
  353. cleaned = self._sanitize_cookie_for_playwright(cookie, self.cookie_domain)
  354. if cleaned:
  355. sanitized.append(cleaned)
  356. if not sanitized:
  357. raise Exception("没有可用的 Cookie(清洗后为空)")
  358. await self.context.add_cookies(sanitized)
  359. async def close_browser(self):
  360. """关闭浏览器"""
  361. if self.context:
  362. await self.context.close()
  363. if self.browser:
  364. await self.browser.close()
  365. async def human_like_delay(self, min_ms: int = 100, max_ms: int = 500):
  366. """模拟人类操作延迟"""
  367. delay = random.randint(min_ms, max_ms) / 1000.0
  368. await asyncio.sleep(delay)
  369. async def human_like_scroll(self, distance: int = None):
  370. """模拟人类滚动"""
  371. if distance is None:
  372. distance = random.randint(200, 500)
  373. # 分多次滚动,模拟真实行为
  374. steps = random.randint(3, 6)
  375. step_distance = distance // steps
  376. for _ in range(steps):
  377. if self.page:
  378. await self.page.evaluate(f"window.scrollBy(0, {step_distance})")
  379. await self.human_like_delay(100, 300)
  380. async def human_like_type(self, selector: str, text: str, clear_first: bool = True):
  381. """模拟人类输入"""
  382. if not self.page:
  383. return
  384. element = self.page.locator(selector)
  385. if await element.count() == 0:
  386. return
  387. await element.click()
  388. if clear_first:
  389. await self.page.keyboard.press("Control+KeyA")
  390. await self.page.keyboard.press("Backspace")
  391. await self.human_like_delay(50, 150)
  392. for char in text:
  393. delay = random.randint(30, 100) / 1000.0
  394. await self.page.keyboard.type(char)
  395. await asyncio.sleep(delay)
  396. async def random_mouse_move(self):
  397. """随机移动鼠标(增加真实感)"""
  398. if not self.page:
  399. return
  400. try:
  401. # 随机移动到页面某处
  402. x = random.randint(100, 1800)
  403. y = random.randint(100, 900)
  404. await self.page.mouse.move(x, y)
  405. await self.human_like_delay(50, 200)
  406. except Exception:
  407. pass
  408. async def save_cookies(self, file_path: str):
  409. """保存 cookies 到文件"""
  410. if self.context:
  411. await self.context.storage_state(path=file_path)
  412. async def capture_screenshot(self) -> str:
  413. """截取当前页面截图,返回 Base64 编码"""
  414. import base64
  415. if not self.page:
  416. return ""
  417. try:
  418. screenshot_bytes = await self.page.screenshot(type="jpeg", quality=80)
  419. return base64.b64encode(screenshot_bytes).decode("utf-8")
  420. except Exception as e:
  421. print(f"[{self.platform_name}] 截图失败: {e}")
  422. return ""
  423. async def save_screenshot_to_file(
  424. self, directory: str = None, filename_prefix: str = "publish_failed"
  425. ) -> str:
  426. """
  427. 保存截图到指定目录,返回文件路径
  428. Args:
  429. directory: 截图保存目录,默认为 server/python/screenshots
  430. filename_prefix: 文件名前缀
  431. Returns:
  432. str: 保存的文件路径,失败返回空字符串
  433. """
  434. if not self.page:
  435. return ""
  436. try:
  437. if directory is None:
  438. current_dir = os.path.dirname(
  439. os.path.dirname(os.path.abspath(__file__))
  440. )
  441. directory = os.path.join(current_dir, "screenshots")
  442. directory = os.path.abspath(directory)
  443. os.makedirs(directory, exist_ok=True)
  444. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  445. task_info = f"_task{self.publish_task_id}" if self.publish_task_id else ""
  446. account_info = (
  447. f"_acc{self.publish_account_id}" if self.publish_account_id else ""
  448. )
  449. filename = f"{filename_prefix}_{self.platform_name}{task_info}{account_info}_{timestamp}.png"
  450. filepath = os.path.join(directory, filename)
  451. await self.page.screenshot(path=filepath, type="png")
  452. print(f"[{self.platform_name}] 截图已保存: {filepath}")
  453. return filepath
  454. except Exception as e:
  455. print(f"[{self.platform_name}] 保存截图失败: {e}")
  456. return ""
  457. async def request_sms_code_from_frontend(
  458. self, phone: str = "", timeout_seconds: int = 120, message: str = ""
  459. ) -> str:
  460. node_api_url = os.environ.get("NODEJS_API_URL", "http://localhost:3000").rstrip(
  461. "/"
  462. )
  463. internal_api_key = os.environ.get(
  464. "INTERNAL_API_KEY", "internal-api-key-default"
  465. )
  466. if not self.user_id:
  467. raise Exception("缺少 user_id,无法请求前端输入验证码")
  468. captcha_task_id = f"py_{self.platform_name}_{uuid.uuid4().hex}"
  469. payload = {
  470. "user_id": self.user_id,
  471. "captcha_task_id": captcha_task_id,
  472. "type": "sms",
  473. "phone": phone or "",
  474. "message": message or "请输入短信验证码",
  475. "timeout_seconds": timeout_seconds,
  476. "publish_task_id": self.publish_task_id,
  477. "publish_account_id": self.publish_account_id,
  478. }
  479. import requests
  480. try:
  481. resp = requests.post(
  482. f"{node_api_url}/api/internal/captcha/request",
  483. headers={
  484. "Content-Type": "application/json",
  485. "X-Internal-API-Key": internal_api_key,
  486. },
  487. json=payload,
  488. timeout=timeout_seconds + 30,
  489. )
  490. except Exception as e:
  491. raise Exception(f"请求前端验证码失败: {e}")
  492. try:
  493. data = resp.json()
  494. except Exception:
  495. raise Exception(f"请求前端验证码失败: HTTP {resp.status_code}")
  496. if resp.status_code >= 400 or not data.get("success"):
  497. raise Exception(
  498. data.get("error")
  499. or data.get("message")
  500. or f"请求前端验证码失败: HTTP {resp.status_code}"
  501. )
  502. code = data.get("code") or ""
  503. if not code:
  504. raise Exception("未收到验证码")
  505. return str(code)
  506. async def ai_analyze_sms_send_state(self, screenshot_base64: str = None) -> dict:
  507. import os
  508. import requests
  509. import json
  510. import re
  511. try:
  512. if not screenshot_base64:
  513. screenshot_base64 = await self.capture_screenshot()
  514. if not screenshot_base64:
  515. return {
  516. "has_sms_modal": False,
  517. "send_button_state": "unknown",
  518. "sent_likely": False,
  519. "block_reason": "unknown",
  520. "suggested_action": "manual_send",
  521. "confidence": 0,
  522. "notes": "无法获取截图",
  523. }
  524. ai_api_key = os.environ.get("DASHSCOPE_API_KEY", "")
  525. ai_base_url = os.environ.get(
  526. "DASHSCOPE_BASE_URL",
  527. "https://dashscope.aliyuncs.com/compatible-mode/v1",
  528. )
  529. ai_vision_model = os.environ.get("AI_VISION_MODEL", "qwen-vl-plus")
  530. if not ai_api_key:
  531. return {
  532. "has_sms_modal": True,
  533. "send_button_state": "unknown",
  534. "sent_likely": False,
  535. "block_reason": "no_ai_key",
  536. "suggested_action": "manual_send",
  537. "confidence": 0,
  538. "notes": "未配置 AI API Key",
  539. }
  540. prompt = """请分析这张网页截图,判断是否处于“短信验证码”验证弹窗/页面,并判断“发送验证码/获取验证码”是否已经触发成功。
  541. 你需要重点识别:
  542. 1) 是否存在短信验证码弹窗(包含“请输入验证码/短信验证码/手机号验证/获取验证码/发送验证码”等)
  543. 2) 发送按钮状态:enabled / disabled / countdown(出现xx秒) / hidden / unknown
  544. 3) 是否已发送成功:例如出现倒计时、按钮禁用、出现“已发送/重新发送/xx秒后重试”等
  545. 4) 是否被阻塞:例如出现滑块/人机验证、频繁发送、风控提示、网络异常等
  546. 请以 JSON 返回:
  547. ```json
  548. {
  549. "has_sms_modal": true,
  550. "send_button_state": "enabled|disabled|countdown|hidden|unknown",
  551. "sent_likely": true,
  552. "block_reason": "none|need_click_send|slider|risk|rate_limit|network|unknown",
  553. "suggested_action": "wait|click_send|solve_slider|manual_send",
  554. "confidence": 0-100,
  555. "notes": "一句话说明你看到的证据"
  556. }
  557. ```"""
  558. headers = {
  559. "Authorization": f"Bearer {ai_api_key}",
  560. "Content-Type": "application/json",
  561. }
  562. payload = {
  563. "model": ai_vision_model,
  564. "messages": [
  565. {
  566. "role": "user",
  567. "content": [
  568. {
  569. "type": "image_url",
  570. "image_url": {
  571. "url": f"data:image/jpeg;base64,{screenshot_base64}"
  572. },
  573. },
  574. {"type": "text", "text": prompt},
  575. ],
  576. }
  577. ],
  578. "max_tokens": 500,
  579. }
  580. response = requests.post(
  581. f"{ai_base_url}/chat/completions",
  582. headers=headers,
  583. json=payload,
  584. timeout=30,
  585. )
  586. if response.status_code != 200:
  587. return {
  588. "has_sms_modal": True,
  589. "send_button_state": "unknown",
  590. "sent_likely": False,
  591. "block_reason": "network",
  592. "suggested_action": "manual_send",
  593. "confidence": 0,
  594. "notes": f"AI API 返回错误 {response.status_code}",
  595. }
  596. result = response.json()
  597. ai_response = (
  598. result.get("choices", [{}])[0].get("message", {}).get("content", "")
  599. )
  600. json_match = re.search(r"```json\\s*([\\s\\S]*?)\\s*```", ai_response)
  601. if json_match:
  602. json_str = json_match.group(1)
  603. else:
  604. json_match = re.search(r"\\{[\\s\\S]*\\}", ai_response)
  605. json_str = json_match.group(0) if json_match else "{}"
  606. try:
  607. data = json.loads(json_str)
  608. except Exception:
  609. data = {}
  610. return {
  611. "has_sms_modal": bool(data.get("has_sms_modal", True)),
  612. "send_button_state": data.get("send_button_state", "unknown"),
  613. "sent_likely": bool(data.get("sent_likely", False)),
  614. "block_reason": data.get("block_reason", "unknown"),
  615. "suggested_action": data.get("suggested_action", "manual_send"),
  616. "confidence": int(data.get("confidence", 0) or 0),
  617. "notes": data.get("notes", ""),
  618. }
  619. except Exception as e:
  620. return {
  621. "has_sms_modal": True,
  622. "send_button_state": "unknown",
  623. "sent_likely": False,
  624. "block_reason": "unknown",
  625. "suggested_action": "manual_send",
  626. "confidence": 0,
  627. "notes": f"AI 分析异常: {e}",
  628. }
  629. async def sync_cookies_to_node(self, cookies: list) -> bool:
  630. import os
  631. import json
  632. import requests
  633. if not self.user_id or not self.publish_account_id:
  634. return False
  635. node_api_url = os.environ.get("NODEJS_API_URL", "http://localhost:3000").rstrip(
  636. "/"
  637. )
  638. internal_api_key = os.environ.get(
  639. "INTERNAL_API_KEY", "internal-api-key-default"
  640. )
  641. try:
  642. payload = {
  643. "user_id": int(self.user_id),
  644. "account_id": int(self.publish_account_id),
  645. "cookies": json.dumps(cookies, ensure_ascii=False),
  646. }
  647. resp = requests.post(
  648. f"{node_api_url}/api/internal/accounts/update-cookies",
  649. headers={
  650. "Content-Type": "application/json",
  651. "X-Internal-API-Key": internal_api_key,
  652. },
  653. json=payload,
  654. timeout=30,
  655. )
  656. if resp.status_code >= 400:
  657. return False
  658. data = resp.json() if resp.content else {}
  659. return bool(data.get("success", True))
  660. except Exception:
  661. return False
  662. async def ai_suggest_playwright_selector(
  663. self, goal: str, screenshot_base64: str = None
  664. ) -> dict:
  665. import os
  666. import requests
  667. import json
  668. import re
  669. try:
  670. if not screenshot_base64:
  671. screenshot_base64 = await self.capture_screenshot()
  672. if not screenshot_base64:
  673. return {
  674. "has_selector": False,
  675. "selector": "",
  676. "confidence": 0,
  677. "notes": "无法获取截图",
  678. }
  679. ai_api_key = os.environ.get("DASHSCOPE_API_KEY", "")
  680. ai_base_url = os.environ.get(
  681. "DASHSCOPE_BASE_URL",
  682. "https://dashscope.aliyuncs.com/compatible-mode/v1",
  683. )
  684. ai_vision_model = os.environ.get("AI_VISION_MODEL", "qwen-vl-plus")
  685. if not ai_api_key:
  686. return {
  687. "has_selector": False,
  688. "selector": "",
  689. "confidence": 0,
  690. "notes": "未配置 AI API Key",
  691. }
  692. prompt = f"""请分析这张网页截图,给出一个 Playwright Python 可用的 selector(用于 page.locator(selector))来完成目标操作。
  693. 目标:{goal}
  694. 要求:
  695. 1) selector 尽量稳定(优先 role/text/aria,其次 class,避免过度依赖随机 class)
  696. 2) selector 必须是 Playwright 支持的选择器语法(如:text="发布"、button:has-text("发布")、[role="button"]:has-text("发布") 等)
  697. 3) 只返回一个最优 selector
  698. 以 JSON 返回:
  699. ```json
  700. {{
  701. "has_selector": true,
  702. "selector": "button:has-text(\\"发布\\")",
  703. "confidence": 0-100,
  704. "notes": "你依据的页面证据"
  705. }}
  706. ```"""
  707. headers = {
  708. "Authorization": f"Bearer {ai_api_key}",
  709. "Content-Type": "application/json",
  710. }
  711. payload = {
  712. "model": ai_vision_model,
  713. "messages": [
  714. {
  715. "role": "user",
  716. "content": [
  717. {
  718. "type": "image_url",
  719. "image_url": {
  720. "url": f"data:image/jpeg;base64,{screenshot_base64}"
  721. },
  722. },
  723. {"type": "text", "text": prompt},
  724. ],
  725. }
  726. ],
  727. "max_tokens": 300,
  728. }
  729. response = requests.post(
  730. f"{ai_base_url}/chat/completions",
  731. headers=headers,
  732. json=payload,
  733. timeout=30,
  734. )
  735. if response.status_code != 200:
  736. return {
  737. "has_selector": False,
  738. "selector": "",
  739. "confidence": 0,
  740. "notes": f"AI API 错误 {response.status_code}",
  741. }
  742. result = response.json()
  743. ai_response = (
  744. result.get("choices", [{}])[0].get("message", {}).get("content", "")
  745. )
  746. json_match = re.search(r"```json\\s*([\\s\\S]*?)\\s*```", ai_response)
  747. if json_match:
  748. json_str = json_match.group(1)
  749. else:
  750. json_match = re.search(r"\\{[\\s\\S]*\\}", ai_response)
  751. json_str = json_match.group(0) if json_match else "{}"
  752. try:
  753. data = json.loads(json_str)
  754. except Exception:
  755. data = {}
  756. selector = str(data.get("selector", "") or "").strip()
  757. has_selector = bool(data.get("has_selector", False)) and bool(selector)
  758. confidence = int(data.get("confidence", 0) or 0)
  759. notes = str(data.get("notes", "") or "")
  760. if not has_selector:
  761. return {
  762. "has_selector": False,
  763. "selector": "",
  764. "confidence": confidence,
  765. "notes": notes or "未给出 selector",
  766. }
  767. return {
  768. "has_selector": True,
  769. "selector": selector,
  770. "confidence": confidence,
  771. "notes": notes,
  772. }
  773. except Exception as e:
  774. return {
  775. "has_selector": False,
  776. "selector": "",
  777. "confidence": 0,
  778. "notes": f"AI selector 异常: {e}",
  779. }
  780. async def ai_check_captcha(self, screenshot_base64: str = None) -> dict:
  781. """
  782. 使用 AI 分析截图检测验证码
  783. Args:
  784. screenshot_base64: 截图的 Base64 编码,如果为空则自动获取当前页面截图
  785. Returns:
  786. dict: {
  787. "has_captcha": bool, # 是否有验证码
  788. "captcha_type": str, # 验证码类型: slider, image, phone, rotate, puzzle
  789. "captcha_description": str, # 验证码描述
  790. "confidence": float, # 置信度 0-100
  791. "need_headful": bool # 是否需要切换到有头浏览器
  792. }
  793. """
  794. import os
  795. import requests
  796. try:
  797. # 获取截图
  798. if not screenshot_base64:
  799. screenshot_base64 = await self.capture_screenshot()
  800. if not screenshot_base64:
  801. print(f"[{self.platform_name}] AI验证码检测: 无法获取截图")
  802. return {
  803. "has_captcha": False,
  804. "captcha_type": "",
  805. "captcha_description": "",
  806. "confidence": 0,
  807. "need_headful": False,
  808. }
  809. # 获取 AI 配置
  810. ai_api_key = os.environ.get("DASHSCOPE_API_KEY", "")
  811. ai_base_url = os.environ.get(
  812. "DASHSCOPE_BASE_URL",
  813. "https://dashscope.aliyuncs.com/compatible-mode/v1",
  814. )
  815. ai_vision_model = os.environ.get("AI_VISION_MODEL", "qwen-vl-plus")
  816. if not ai_api_key:
  817. print(
  818. f"[{self.platform_name}] AI验证码检测: 未配置 AI API Key,使用传统方式检测"
  819. )
  820. return await self._traditional_captcha_check()
  821. # 构建 AI 请求
  822. prompt = """请分析这张网页截图,判断页面上是否存在验证码。
  823. 请检查以下类型的验证码:
  824. 1. 滑块验证码(需要滑动滑块到指定位置)
  825. 2. 图片验证码(需要选择正确的图片、点击图片上的文字等)
  826. 3. 旋转验证码(需要旋转图片到正确角度)
  827. 4. 拼图验证码(需要拖动拼图块到正确位置)
  828. 5. 手机验证码(需要输入手机收到的验证码)
  829. 6. 计算验证码(需要输入计算结果)
  830. 请以 JSON 格式返回结果:
  831. ```json
  832. {
  833. "has_captcha": true/false,
  834. "captcha_type": "slider/image/phone/rotate/puzzle/calculate/none",
  835. "captcha_description": "验证码的具体描述",
  836. "confidence": 0-100
  837. }
  838. ```
  839. 注意:
  840. - 如果页面有明显的验证码弹窗或验证区域,has_captcha 为 true
  841. - 如果只是普通的登录页面或表单,没有特殊的验证步骤,has_captcha 为 false
  842. - confidence 表示你对判断结果的信心,100 表示非常确定"""
  843. headers = {
  844. "Authorization": f"Bearer {ai_api_key}",
  845. "Content-Type": "application/json",
  846. }
  847. payload = {
  848. "model": ai_vision_model,
  849. "messages": [
  850. {
  851. "role": "user",
  852. "content": [
  853. {
  854. "type": "image_url",
  855. "image_url": {
  856. "url": f"data:image/jpeg;base64,{screenshot_base64}"
  857. },
  858. },
  859. {"type": "text", "text": prompt},
  860. ],
  861. }
  862. ],
  863. "max_tokens": 500,
  864. }
  865. print(f"[{self.platform_name}] AI验证码检测: 正在分析截图...")
  866. response = requests.post(
  867. f"{ai_base_url}/chat/completions",
  868. headers=headers,
  869. json=payload,
  870. timeout=30,
  871. )
  872. if response.status_code != 200:
  873. print(
  874. f"[{self.platform_name}] AI验证码检测: API 返回错误 {response.status_code}"
  875. )
  876. return await self._traditional_captcha_check()
  877. result = response.json()
  878. ai_response = (
  879. result.get("choices", [{}])[0].get("message", {}).get("content", "")
  880. )
  881. print(f"[{self.platform_name}] AI验证码检测响应: {ai_response[:200]}...")
  882. # 解析 AI 响应
  883. import re
  884. json_match = re.search(r"```json\s*([\s\S]*?)\s*```", ai_response)
  885. if json_match:
  886. json_str = json_match.group(1)
  887. else:
  888. # 尝试直接解析
  889. json_match = re.search(r"\{[\s\S]*\}", ai_response)
  890. if json_match:
  891. json_str = json_match.group(0)
  892. else:
  893. json_str = "{}"
  894. try:
  895. ai_result = json.loads(json_str)
  896. except:
  897. ai_result = {}
  898. has_captcha = ai_result.get("has_captcha", False)
  899. captcha_type = ai_result.get("captcha_type", "")
  900. captcha_description = ai_result.get("captcha_description", "")
  901. confidence = ai_result.get("confidence", 0)
  902. # 如果检测到验证码,需要切换到有头浏览器
  903. need_headful = has_captcha and captcha_type not in ["none", ""]
  904. print(
  905. f"[{self.platform_name}] AI验证码检测结果: has_captcha={has_captcha}, type={captcha_type}, confidence={confidence}"
  906. )
  907. return {
  908. "has_captcha": has_captcha,
  909. "captcha_type": captcha_type if captcha_type != "none" else "",
  910. "captcha_description": captcha_description,
  911. "confidence": confidence,
  912. "need_headful": need_headful,
  913. }
  914. except Exception as e:
  915. print(f"[{self.platform_name}] AI验证码检测异常: {e}")
  916. import traceback
  917. traceback.print_exc()
  918. return await self._traditional_captcha_check()
  919. async def _traditional_captcha_check(self) -> dict:
  920. """传统方式检测验证码(基于 DOM 元素)"""
  921. if not self.page:
  922. return {
  923. "has_captcha": False,
  924. "captcha_type": "",
  925. "captcha_description": "",
  926. "confidence": 0,
  927. "need_headful": False,
  928. }
  929. try:
  930. # 检查常见的验证码选择器
  931. captcha_selectors = [
  932. # 滑块验证码
  933. ('[class*="slider"]', "slider", "滑块验证码"),
  934. ('[class*="slide-verify"]', "slider", "滑块验证码"),
  935. ('text="滑动"', "slider", "滑块验证码"),
  936. ('text="拖动"', "slider", "滑块验证码"),
  937. # 图片验证码
  938. ('[class*="captcha"]', "image", "图片验证码"),
  939. ('[class*="verify-img"]', "image", "图片验证码"),
  940. ('text="点击"', "image", "图片验证码"),
  941. ('text="选择"', "image", "图片验证码"),
  942. # 手机验证码
  943. ('text="验证码"', "phone", "手机验证码"),
  944. ('text="获取验证码"', "phone", "手机验证码"),
  945. ('[class*="sms-code"]', "phone", "手机验证码"),
  946. # 旋转验证码
  947. ('text="旋转"', "rotate", "旋转验证码"),
  948. ('[class*="rotate"]', "rotate", "旋转验证码"),
  949. ]
  950. for selector, captcha_type, description in captcha_selectors:
  951. try:
  952. count = await self.page.locator(selector).count()
  953. if count > 0:
  954. # 检查是否可见
  955. element = self.page.locator(selector).first
  956. if await element.is_visible():
  957. print(
  958. f"[{self.platform_name}] 传统检测: 发现验证码 - {selector}"
  959. )
  960. return {
  961. "has_captcha": True,
  962. "captcha_type": captcha_type,
  963. "captcha_description": description,
  964. "confidence": 80,
  965. "need_headful": True,
  966. }
  967. except:
  968. pass
  969. return {
  970. "has_captcha": False,
  971. "captcha_type": "",
  972. "captcha_description": "",
  973. "confidence": 80,
  974. "need_headful": False,
  975. }
  976. except Exception as e:
  977. print(f"[{self.platform_name}] 传统验证码检测异常: {e}")
  978. return {
  979. "has_captcha": False,
  980. "captcha_type": "",
  981. "captcha_description": "",
  982. "confidence": 0,
  983. "need_headful": False,
  984. }
  985. async def get_page_url(self) -> str:
  986. """获取当前页面 URL"""
  987. if not self.page:
  988. return ""
  989. try:
  990. return self.page.url
  991. except:
  992. return ""
  993. async def check_publish_status(self) -> dict:
  994. """
  995. 检查发布状态
  996. 返回: {status, screenshot_base64, page_url, message}
  997. """
  998. if not self.page:
  999. return {"status": "error", "message": "页面未初始化"}
  1000. try:
  1001. screenshot = await self.capture_screenshot()
  1002. page_url = await self.get_page_url()
  1003. # 检查常见的成功/失败标志
  1004. page_content = await self.page.content()
  1005. # 检查成功标志
  1006. success_keywords = ["发布成功", "上传成功", "发表成功", "提交成功"]
  1007. for keyword in success_keywords:
  1008. if keyword in page_content:
  1009. return {
  1010. "status": "success",
  1011. "screenshot_base64": screenshot,
  1012. "page_url": page_url,
  1013. "message": "发布成功",
  1014. }
  1015. # 检查验证码标志
  1016. captcha_keywords = [
  1017. "验证码",
  1018. "身份验证",
  1019. "请完成验证",
  1020. "滑动验证",
  1021. "图形验证",
  1022. ]
  1023. for keyword in captcha_keywords:
  1024. if keyword in page_content:
  1025. return {
  1026. "status": "need_captcha",
  1027. "screenshot_base64": screenshot,
  1028. "page_url": page_url,
  1029. "message": f"检测到{keyword}",
  1030. }
  1031. # 检查失败标志
  1032. fail_keywords = ["发布失败", "上传失败", "提交失败", "操作失败"]
  1033. for keyword in fail_keywords:
  1034. if keyword in page_content:
  1035. return {
  1036. "status": "failed",
  1037. "screenshot_base64": screenshot,
  1038. "page_url": page_url,
  1039. "message": keyword,
  1040. }
  1041. # 默认返回处理中
  1042. return {
  1043. "status": "processing",
  1044. "screenshot_base64": screenshot,
  1045. "page_url": page_url,
  1046. "message": "处理中",
  1047. }
  1048. except Exception as e:
  1049. return {
  1050. "status": "error",
  1051. "screenshot_base64": "",
  1052. "page_url": "",
  1053. "message": str(e),
  1054. }
  1055. async def wait_for_upload_complete(self, success_selector: str, timeout: int = 300):
  1056. """等待上传完成"""
  1057. if not self.page:
  1058. raise Exception("Page not initialized")
  1059. for _ in range(timeout // 3):
  1060. try:
  1061. count = await self.page.locator(success_selector).count()
  1062. if count > 0:
  1063. return True
  1064. except:
  1065. pass
  1066. await asyncio.sleep(3)
  1067. self.report_progress(30, "正在上传视频...")
  1068. return False
  1069. @abstractmethod
  1070. async def publish(self, cookies: str, params: PublishParams) -> PublishResult:
  1071. """
  1072. 发布视频 - 子类必须实现
  1073. Args:
  1074. cookies: cookie 字符串或 JSON
  1075. params: 发布参数
  1076. Returns:
  1077. PublishResult: 发布结果
  1078. """
  1079. pass
  1080. async def get_works(
  1081. self, cookies: str, page: int = 0, page_size: int = 20
  1082. ) -> WorksResult:
  1083. """
  1084. 获取作品列表 - 子类可覆盖实现
  1085. Args:
  1086. cookies: cookie 字符串或 JSON
  1087. page: 页码(从0开始)
  1088. page_size: 每页数量
  1089. Returns:
  1090. WorksResult: 作品列表结果
  1091. """
  1092. return WorksResult(
  1093. success=False,
  1094. platform=self.platform_name,
  1095. error="该平台暂不支持获取作品列表",
  1096. )
  1097. async def get_comments(
  1098. self, cookies: str, work_id: str, cursor: str = ""
  1099. ) -> CommentsResult:
  1100. """
  1101. 获取作品评论 - 子类可覆盖实现
  1102. Args:
  1103. cookies: cookie 字符串或 JSON
  1104. work_id: 作品ID
  1105. cursor: 分页游标
  1106. Returns:
  1107. CommentsResult: 评论列表结果
  1108. """
  1109. return CommentsResult(
  1110. success=False,
  1111. platform=self.platform_name,
  1112. work_id=work_id,
  1113. error="该平台暂不支持获取评论",
  1114. )
  1115. async def run(self, cookies: str, params: PublishParams) -> PublishResult:
  1116. """
  1117. 运行发布任务
  1118. 包装了 publish 方法,添加了异常处理和资源清理
  1119. 发布失败时自动保存截图到 uploads/screenshots 目录
  1120. """
  1121. try:
  1122. result = await self.publish(cookies, params)
  1123. if not result.success and self.page:
  1124. screenshot_path = await self.save_screenshot_to_file()
  1125. if screenshot_path:
  1126. result.screenshot_path = screenshot_path
  1127. return result
  1128. except Exception as e:
  1129. import traceback
  1130. traceback.print_exc()
  1131. screenshot_path = ""
  1132. if self.page:
  1133. screenshot_path = await self.save_screenshot_to_file()
  1134. return PublishResult(
  1135. success=False,
  1136. platform=self.platform_name,
  1137. error=str(e),
  1138. screenshot_path=screenshot_path,
  1139. )
  1140. finally:
  1141. await self.close_browser()
  1142. async def run_get_works(
  1143. self, cookies: str, page: int = 0, page_size: int = 20
  1144. ) -> WorksResult:
  1145. """
  1146. 运行获取作品任务
  1147. """
  1148. try:
  1149. return await self.get_works(cookies, page, page_size)
  1150. except Exception as e:
  1151. import traceback
  1152. traceback.print_exc()
  1153. return WorksResult(success=False, platform=self.platform_name, error=str(e))
  1154. finally:
  1155. await self.close_browser()
  1156. async def run_get_comments(
  1157. self, cookies: str, work_id: str, cursor: str = ""
  1158. ) -> CommentsResult:
  1159. """
  1160. 运行获取评论任务
  1161. """
  1162. try:
  1163. return await self.get_comments(cookies, work_id, cursor)
  1164. except Exception as e:
  1165. import traceback
  1166. traceback.print_exc()
  1167. return CommentsResult(
  1168. success=False,
  1169. platform=self.platform_name,
  1170. work_id=work_id,
  1171. error=str(e),
  1172. )
  1173. finally:
  1174. await self.close_browser()
  1175. async def check_login_status(self, cookies: str) -> dict:
  1176. """
  1177. 检查 Cookie 登录状态(通过浏览器访问后台页面检测)
  1178. Args:
  1179. cookies: cookie 字符串或 JSON
  1180. Returns:
  1181. dict: {
  1182. "success": True,
  1183. "valid": True/False,
  1184. "need_login": True/False,
  1185. "message": "状态描述"
  1186. }
  1187. """
  1188. try:
  1189. await self.init_browser()
  1190. cookie_list = self.parse_cookies(cookies)
  1191. await self.set_cookies(cookie_list)
  1192. if not self.page:
  1193. raise Exception("Page not initialized")
  1194. # 访问平台后台首页
  1195. home_url = self.login_url
  1196. print(f"[{self.platform_name}] 访问后台页面: {home_url}")
  1197. await self.page.goto(home_url, wait_until="domcontentloaded", timeout=30000)
  1198. await asyncio.sleep(3)
  1199. # 检查当前 URL 是否被重定向到登录页
  1200. current_url = self.page.url
  1201. print(f"[{self.platform_name}] 当前 URL: {current_url}")
  1202. # 登录页特征
  1203. login_indicators = ["login", "passport", "signin", "auth"]
  1204. is_login_page = any(
  1205. indicator in current_url.lower() for indicator in login_indicators
  1206. )
  1207. # 检查页面是否有登录弹窗
  1208. need_login = is_login_page
  1209. # 风控/验证码特征
  1210. risk_indicators = [
  1211. "captcha",
  1212. "verify",
  1213. "challenge",
  1214. "risk",
  1215. "security",
  1216. "safe",
  1217. "protect",
  1218. "slider",
  1219. ]
  1220. need_verification = any(
  1221. indicator in current_url.lower() for indicator in risk_indicators
  1222. )
  1223. if not need_login:
  1224. # 检查页面内容是否有登录提示
  1225. login_selectors = [
  1226. 'text="请先登录"',
  1227. 'text="登录后继续"',
  1228. 'text="请登录"',
  1229. '[class*="login-modal"]',
  1230. '[class*="login-dialog"]',
  1231. '[class*="login-popup"]',
  1232. ]
  1233. for selector in login_selectors:
  1234. try:
  1235. if await self.page.locator(selector).count() > 0:
  1236. need_login = True
  1237. print(f"[{self.platform_name}] 检测到登录弹窗: {selector}")
  1238. break
  1239. except:
  1240. pass
  1241. if not need_login and not need_verification:
  1242. verification_selectors = [
  1243. 'text="安全验证"',
  1244. 'text="验证码"',
  1245. 'text="人机验证"',
  1246. 'text="滑块"',
  1247. 'text="请完成验证"',
  1248. 'text="系统检测到异常"',
  1249. 'text="访问受限"',
  1250. 'text="行为异常"',
  1251. ]
  1252. for selector in verification_selectors:
  1253. try:
  1254. if await self.page.locator(selector).count() > 0:
  1255. need_verification = True
  1256. print(
  1257. f"[{self.platform_name}] 检测到风控/验证码提示: {selector}"
  1258. )
  1259. break
  1260. except:
  1261. pass
  1262. if need_login:
  1263. return {
  1264. "success": True,
  1265. "valid": False,
  1266. "need_login": True,
  1267. "message": "Cookie 已过期,需要重新登录",
  1268. }
  1269. elif need_verification:
  1270. return {
  1271. "success": True,
  1272. "valid": False,
  1273. "need_login": True,
  1274. "message": "触发风控/需要验证",
  1275. }
  1276. else:
  1277. return {
  1278. "success": True,
  1279. "valid": True,
  1280. "need_login": False,
  1281. "message": "登录状态有效",
  1282. }
  1283. except Exception as e:
  1284. import traceback
  1285. traceback.print_exc()
  1286. return {
  1287. "success": False,
  1288. "valid": False,
  1289. "need_login": True,
  1290. "error": str(e),
  1291. }
  1292. finally:
  1293. await self.close_browser()