baijiahao.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  1. # -*- coding: utf-8 -*-
  2. """
  3. 百家号视频发布器
  4. """
  5. import asyncio
  6. import json
  7. from typing import List
  8. from datetime import datetime
  9. from .base import (
  10. BasePublisher, PublishParams, PublishResult,
  11. WorkItem, WorksResult, CommentItem, CommentsResult
  12. )
  13. class BaijiahaoPublisher(BasePublisher):
  14. """
  15. 百家号视频发布器
  16. 使用 Playwright 自动化操作百家号创作者中心
  17. """
  18. platform_name = "baijiahao"
  19. login_url = "https://baijiahao.baidu.com/"
  20. publish_url = "https://baijiahao.baidu.com/builder/rc/edit?type=video"
  21. cookie_domain = ".baidu.com"
  22. # 登录检测配置
  23. login_check_url = "https://baijiahao.baidu.com/builder/rc/home"
  24. login_indicators = ["passport.baidu.com", "/login", "wappass.baidu.com"]
  25. login_selectors = ['text="登录"', 'text="请登录"', '[class*="login-btn"]']
  26. async def get_account_info(self, cookies: str) -> dict:
  27. """
  28. 获取百家号账号信息
  29. 使用直接 HTTP API 调用,不使用浏览器
  30. """
  31. import aiohttp
  32. print(f"\n{'='*60}")
  33. print(f"[{self.platform_name}] 获取账号信息 (使用 API)")
  34. print(f"{'='*60}")
  35. try:
  36. # 解析 cookies
  37. cookie_list = self.parse_cookies(cookies)
  38. cookie_dict = {c['name']: c['value'] for c in cookie_list}
  39. # 重要:百家号需要先访问主页建立会话上下文
  40. print(f"[{self.platform_name}] 第一步:访问主页建立会话...")
  41. session_headers = {
  42. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
  43. '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',
  44. # Cookie 由 session 管理,不手动设置
  45. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  46. 'Accept-Encoding': 'gzip, deflate, br',
  47. 'Connection': 'keep-alive',
  48. 'Upgrade-Insecure-Requests': '1',
  49. 'Sec-Fetch-Dest': 'document',
  50. 'Sec-Fetch-Mode': 'navigate',
  51. 'Sec-Fetch-Site': 'none',
  52. 'Sec-Fetch-User': '?1',
  53. 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
  54. 'sec-ch-ua-mobile': '?0',
  55. 'sec-ch-ua-platform': '"Windows"'
  56. }
  57. headers = {
  58. 'Accept': 'application/json, text/plain, */*',
  59. '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',
  60. # Cookie 由 session 管理,不手动设置
  61. 'Referer': 'https://baijiahao.baidu.com/builder/rc/home',
  62. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  63. 'Accept-Encoding': 'gzip, deflate, br',
  64. 'Connection': 'keep-alive',
  65. 'Sec-Fetch-Dest': 'empty',
  66. 'Sec-Fetch-Mode': 'cors',
  67. 'Sec-Fetch-Site': 'same-origin',
  68. 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
  69. 'sec-ch-ua-mobile': '?0',
  70. 'sec-ch-ua-platform': '"Windows"'
  71. }
  72. # 使用 cookies 参数初始化 session,让 aiohttp 自动管理 cookie 更新
  73. async with aiohttp.ClientSession(cookies=cookie_dict) as session:
  74. # 步骤 0: 先访问主页建立会话上下文(关键步骤!)
  75. print(f"[{self.platform_name}] [0/4] 访问主页建立会话上下文...")
  76. async with session.get(
  77. 'https://baijiahao.baidu.com/builder/rc/home',
  78. headers=session_headers,
  79. timeout=aiohttp.ClientTimeout(total=30)
  80. ) as home_response:
  81. home_status = home_response.status
  82. print(f"[{self.platform_name}] 主页访问状态: {home_status}")
  83. # 获取响应头中的新cookies(如果有)
  84. if 'Set-Cookie' in home_response.headers:
  85. new_cookies = home_response.headers['Set-Cookie']
  86. print(f"[{self.platform_name}] 获取到新的会话Cookie")
  87. # 这里可以处理新的cookies,但暂时跳过复杂处理
  88. # 短暂等待确保会话建立
  89. await asyncio.sleep(1)
  90. # 步骤 1: 获取账号基本信息
  91. print(f"[{self.platform_name}] [1/4] 调用 appinfo API...")
  92. async with session.get(
  93. 'https://baijiahao.baidu.com/builder/app/appinfo',
  94. headers=headers,
  95. timeout=aiohttp.ClientTimeout(total=30)
  96. ) as response:
  97. appinfo_result = await response.json()
  98. print(f"[{self.platform_name}] appinfo API 完整响应: {json.dumps(appinfo_result, ensure_ascii=False)[:500]}")
  99. print(f"[{self.platform_name}] appinfo API 响应: errno={appinfo_result.get('errno')}")
  100. # 检查登录状态
  101. if appinfo_result.get('errno') != 0:
  102. error_msg = appinfo_result.get('errmsg', '未知错误')
  103. errno = appinfo_result.get('errno')
  104. print(f"[{self.platform_name}] API 返回错误: errno={errno}, msg={error_msg}")
  105. # errno 110 表示未登录
  106. if errno == 110:
  107. return {
  108. "success": False,
  109. "error": "Cookie 已失效,需要重新登录",
  110. "need_login": True
  111. }
  112. # errno 10001402 表示分散认证问题,尝试重新访问主页后重试
  113. if errno == 10001402:
  114. print(f"[{self.platform_name}] 检测到分散认证问题,尝试重新访问主页...")
  115. await asyncio.sleep(2)
  116. # 重新访问主页
  117. async with session.get(
  118. 'https://baijiahao.baidu.com/builder/rc/home',
  119. headers=session_headers,
  120. timeout=aiohttp.ClientTimeout(total=30)
  121. ) as retry_home_response:
  122. print(f"[{self.platform_name}] 重新访问主页状态: {retry_home_response.status}")
  123. await asyncio.sleep(1)
  124. # 重试 API 调用
  125. async with session.get(
  126. 'https://baijiahao.baidu.com/builder/app/appinfo',
  127. headers=headers,
  128. timeout=aiohttp.ClientTimeout(total=30)
  129. ) as retry_response:
  130. retry_result = await retry_response.json()
  131. if retry_result.get('errno') == 0:
  132. print(f"[{self.platform_name}] 分散认证问题已解决")
  133. # 使用重试成功的结果继续处理
  134. appinfo_result = retry_result
  135. else:
  136. print(f"[{self.platform_name}] 重试仍然失败")
  137. return {
  138. "success": False,
  139. "error": f"分散认证问题: {error_msg}",
  140. "need_login": True
  141. }
  142. return {
  143. "success": False,
  144. "error": error_msg,
  145. "need_login": True
  146. }
  147. # 获取用户数据
  148. user_data = appinfo_result.get('data', {}).get('user', {})
  149. if not user_data:
  150. return {
  151. "success": False,
  152. "error": "无法获取用户信息",
  153. "need_login": True
  154. }
  155. # 检查账号状态
  156. status = user_data.get('status', '')
  157. # 有效的账号状态:audit(审核中), pass(已通过), normal(正常), newbie(新手)
  158. valid_statuses = ['audit', 'pass', 'normal', 'newbie']
  159. if status not in valid_statuses:
  160. print(f"[{self.platform_name}] 账号状态异常: {status}")
  161. # 提取基本信息
  162. account_name = user_data.get('name') or user_data.get('uname') or '百家号账号'
  163. app_id = user_data.get('app_id') or user_data.get('id', 0)
  164. account_id = str(app_id) if app_id else f"baijiahao_{int(datetime.now().timestamp() * 1000)}"
  165. # 处理头像 URL
  166. avatar_url = user_data.get('avatar') or user_data.get('avatar_unify', '')
  167. if avatar_url and avatar_url.startswith('//'):
  168. avatar_url = 'https:' + avatar_url
  169. print(f"[{self.platform_name}] 账号名称: {account_name}, ID: {account_id}")
  170. # 步骤 2: 获取粉丝数(非关键,失败不影响整体)
  171. fans_count = 0
  172. try:
  173. print(f"[{self.platform_name}] [2/3] 调用 growth/get_info API 获取粉丝数...")
  174. async with session.get(
  175. 'https://baijiahao.baidu.com/cms-ui/rights/growth/get_info',
  176. headers=headers,
  177. timeout=aiohttp.ClientTimeout(total=10)
  178. ) as response:
  179. growth_result = await response.json()
  180. if growth_result.get('errno') == 0:
  181. growth_data = growth_result.get('data', {})
  182. fans_count = int(growth_data.get('fans_num', 0))
  183. print(f"[{self.platform_name}] 粉丝数: {fans_count}")
  184. else:
  185. print(f"[{self.platform_name}] 获取粉丝数失败: {growth_result.get('errmsg')}")
  186. except Exception as e:
  187. print(f"[{self.platform_name}] 获取粉丝数异常(非关键): {e}")
  188. # 步骤 3: 获取作品数量(使用与 Node 端一致的 API)
  189. works_count = 0
  190. try:
  191. print(f"[{self.platform_name}] [3/3] 调用 article/lists API 获取作品数...")
  192. # 使用与 Node 端一致的 API 参数
  193. list_url = 'https://baijiahao.baidu.com/pcui/article/lists?currentPage=1&pageSize=20&search=&type=&collection=&startDate=&endDate=&clearBeforeFetch=false&dynamic=0'
  194. async with session.get(
  195. list_url,
  196. headers={
  197. 'accept': '*/*',
  198. 'user-agent': 'PostmanRuntime/7.51.0',
  199. # cookie 由 session 管理
  200. 'referer': 'https://baijiahao.baidu.com/builder/rc/content',
  201. 'connection': 'keep-alive',
  202. 'accept-encoding': 'gzip, deflate, br',
  203. },
  204. timeout=aiohttp.ClientTimeout(total=30)
  205. ) as response:
  206. response_text = await response.text()
  207. print(f"[{self.platform_name}] ========== Works API Response ==========")
  208. print(f"[{self.platform_name}] Full response: {response_text[:1000]}...") # 只打印前1000字符
  209. print(f"[{self.platform_name}] =========================================")
  210. works_result = json.loads(response_text)
  211. # 处理分散认证问题 (errno=10001402),重试一次
  212. if works_result.get('errno') == 10001402:
  213. print(f"[{self.platform_name}] 分散认证问题 (errno=10001402),3秒后重试...")
  214. await asyncio.sleep(3)
  215. # 重试一次,使用更完整的请求头
  216. retry_headers = headers.copy()
  217. retry_headers.update({
  218. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
  219. 'Cache-Control': 'max-age=0',
  220. 'Upgrade-Insecure-Requests': '1',
  221. })
  222. async with session.get(
  223. list_url,
  224. headers=retry_headers,
  225. timeout=aiohttp.ClientTimeout(total=30)
  226. ) as retry_response:
  227. retry_text = await retry_response.text()
  228. print(f"[{self.platform_name}] ========== Works API Retry Response ==========")
  229. print(f"[{self.platform_name}] Full retry response: {retry_text[:1000]}...")
  230. print(f"[{self.platform_name}] ===============================================")
  231. works_result = json.loads(retry_text)
  232. if works_result.get('errno') == 10001402:
  233. print(f"[{self.platform_name}] 重试仍然失败,返回已获取的账号信息")
  234. works_result = None
  235. if works_result and works_result.get('errno') == 0:
  236. works_data = works_result.get('data', {})
  237. # 优先使用 data.page.totalCount,如果没有则使用 data.total(兼容旧格式)
  238. page_info = works_data.get('page', {})
  239. works_count = int(page_info.get('totalCount', works_data.get('total', 0)))
  240. print(f"[{self.platform_name}] 作品数: {works_count} (from page.totalCount: {page_info.get('totalCount')}, from total: {works_data.get('total')})")
  241. else:
  242. errno = works_result.get('errno') if works_result else 'unknown'
  243. errmsg = works_result.get('errmsg', 'unknown error') if works_result else 'no response'
  244. print(f"[{self.platform_name}] 获取作品数失败: errno={errno}, errmsg={errmsg}")
  245. except Exception as e:
  246. import traceback
  247. print(f"[{self.platform_name}] 获取作品数异常(非关键): {e}")
  248. traceback.print_exc()
  249. # 返回账号信息
  250. account_info = {
  251. "success": True,
  252. "account_id": account_id,
  253. "account_name": account_name,
  254. "avatar_url": avatar_url,
  255. "fans_count": fans_count,
  256. "works_count": works_count,
  257. }
  258. print(f"[{self.platform_name}] ✓ 获取成功: {account_name} (粉丝: {fans_count}, 作品: {works_count})")
  259. return account_info
  260. except Exception as e:
  261. import traceback
  262. traceback.print_exc()
  263. return {
  264. "success": False,
  265. "error": str(e)
  266. }
  267. async def check_captcha(self) -> dict:
  268. """检查页面是否需要验证码"""
  269. if not self.page:
  270. return {'need_captcha': False, 'captcha_type': ''}
  271. try:
  272. # 检查各种验证码
  273. captcha_selectors = [
  274. 'text="请输入验证码"',
  275. 'text="滑动验证"',
  276. '[class*="captcha"]',
  277. '[class*="verify"]',
  278. ]
  279. for selector in captcha_selectors:
  280. try:
  281. if await self.page.locator(selector).count() > 0:
  282. print(f"[{self.platform_name}] 检测到验证码: {selector}")
  283. return {'need_captcha': True, 'captcha_type': 'image'}
  284. except:
  285. pass
  286. # 检查登录弹窗
  287. login_selectors = [
  288. 'text="请登录"',
  289. 'text="登录后继续"',
  290. '[class*="login-dialog"]',
  291. ]
  292. for selector in login_selectors:
  293. try:
  294. if await self.page.locator(selector).count() > 0:
  295. print(f"[{self.platform_name}] 检测到需要登录: {selector}")
  296. return {'need_captcha': True, 'captcha_type': 'login'}
  297. except:
  298. pass
  299. except Exception as e:
  300. print(f"[{self.platform_name}] 验证码检测异常: {e}")
  301. return {'need_captcha': False, 'captcha_type': ''}
  302. async def publish(self, cookies: str, params: PublishParams) -> PublishResult:
  303. """发布视频到百家号"""
  304. import os
  305. print(f"\n{'='*60}")
  306. print(f"[{self.platform_name}] 开始发布视频")
  307. print(f"[{self.platform_name}] 视频路径: {params.video_path}")
  308. print(f"[{self.platform_name}] 标题: {params.title}")
  309. print(f"[{self.platform_name}] Headless: {self.headless}")
  310. print(f"{'='*60}")
  311. self.report_progress(5, "正在初始化浏览器...")
  312. # 初始化浏览器
  313. await self.init_browser()
  314. print(f"[{self.platform_name}] 浏览器初始化完成")
  315. # 解析并设置 cookies
  316. cookie_list = self.parse_cookies(cookies)
  317. print(f"[{self.platform_name}] 解析到 {len(cookie_list)} 个 cookies")
  318. await self.set_cookies(cookie_list)
  319. if not self.page:
  320. raise Exception("Page not initialized")
  321. # 检查视频文件
  322. if not os.path.exists(params.video_path):
  323. raise Exception(f"视频文件不存在: {params.video_path}")
  324. print(f"[{self.platform_name}] 视频文件存在,大小: {os.path.getsize(params.video_path)} bytes")
  325. self.report_progress(10, "正在打开上传页面...")
  326. # 访问视频发布页面(使用新视频发布界面)
  327. video_publish_url = "https://baijiahao.baidu.com/builder/rc/edit?type=videoV2&is_from_cms=1"
  328. await self.page.goto(video_publish_url, wait_until="domcontentloaded", timeout=60000)
  329. await asyncio.sleep(3)
  330. # 检查是否跳转到登录页
  331. current_url = self.page.url
  332. print(f"[{self.platform_name}] 当前页面: {current_url}")
  333. for indicator in self.login_indicators:
  334. if indicator in current_url:
  335. screenshot_base64 = await self.capture_screenshot()
  336. return PublishResult(
  337. success=False,
  338. platform=self.platform_name,
  339. error="Cookie 已过期,需要重新登录",
  340. need_captcha=True,
  341. captcha_type='login',
  342. screenshot_base64=screenshot_base64,
  343. page_url=current_url,
  344. status='need_captcha'
  345. )
  346. # 使用 AI 检查验证码
  347. ai_captcha = await self.ai_check_captcha()
  348. if ai_captcha['has_captcha']:
  349. print(f"[{self.platform_name}] AI检测到验证码: {ai_captcha['captcha_type']}", flush=True)
  350. screenshot_base64 = await self.capture_screenshot()
  351. return PublishResult(
  352. success=False,
  353. platform=self.platform_name,
  354. error=f"检测到{ai_captcha['captcha_type']}验证码,需要使用有头浏览器完成验证",
  355. need_captcha=True,
  356. captcha_type=ai_captcha['captcha_type'],
  357. screenshot_base64=screenshot_base64,
  358. page_url=current_url,
  359. status='need_captcha'
  360. )
  361. # 传统方式检查验证码
  362. captcha_result = await self.check_captcha()
  363. if captcha_result['need_captcha']:
  364. screenshot_base64 = await self.capture_screenshot()
  365. return PublishResult(
  366. success=False,
  367. platform=self.platform_name,
  368. error=f"需要{captcha_result['captcha_type']}验证码,请使用有头浏览器完成验证",
  369. need_captcha=True,
  370. captcha_type=captcha_result['captcha_type'],
  371. screenshot_base64=screenshot_base64,
  372. page_url=current_url,
  373. status='need_captcha'
  374. )
  375. self.report_progress(15, "正在选择视频文件...")
  376. # 等待页面加载完成
  377. await asyncio.sleep(2)
  378. # 关闭可能的弹窗
  379. try:
  380. close_buttons = [
  381. 'button:has-text("我知道了")',
  382. 'button:has-text("知道了")',
  383. '[class*="close"]',
  384. '[class*="modal-close"]',
  385. ]
  386. for btn_selector in close_buttons:
  387. try:
  388. btn = self.page.locator(btn_selector).first
  389. if await btn.count() > 0 and await btn.is_visible():
  390. await btn.click()
  391. await asyncio.sleep(0.5)
  392. except:
  393. pass
  394. except:
  395. pass
  396. # 上传视频 - 尝试多种方式
  397. upload_success = False
  398. # 方法1: 直接通过 file input 上传
  399. try:
  400. file_inputs = await self.page.query_selector_all('input[type="file"]')
  401. print(f"[{self.platform_name}] 找到 {len(file_inputs)} 个文件输入")
  402. for file_input in file_inputs:
  403. try:
  404. await file_input.set_input_files(params.video_path)
  405. upload_success = True
  406. print(f"[{self.platform_name}] 通过 file input 上传成功")
  407. break
  408. except Exception as e:
  409. print(f"[{self.platform_name}] file input 上传失败: {e}")
  410. except Exception as e:
  411. print(f"[{self.platform_name}] 查找 file input 失败: {e}")
  412. # 方法2: 点击上传区域
  413. if not upload_success:
  414. upload_selectors = [
  415. 'div[class*="upload-box"]',
  416. 'div[class*="drag-upload"]',
  417. 'div[class*="uploader"]',
  418. 'div:has-text("点击上传")',
  419. 'div:has-text("选择文件")',
  420. '[class*="upload-area"]',
  421. ]
  422. for selector in upload_selectors:
  423. if upload_success:
  424. break
  425. try:
  426. upload_area = self.page.locator(selector).first
  427. if await upload_area.count() > 0:
  428. print(f"[{self.platform_name}] 尝试点击上传区域: {selector}")
  429. async with self.page.expect_file_chooser(timeout=10000) as fc_info:
  430. await upload_area.click()
  431. file_chooser = await fc_info.value
  432. await file_chooser.set_files(params.video_path)
  433. upload_success = True
  434. print(f"[{self.platform_name}] 通过点击上传区域成功")
  435. break
  436. except Exception as e:
  437. print(f"[{self.platform_name}] 选择器 {selector} 失败: {e}")
  438. if not upload_success:
  439. screenshot_base64 = await self.capture_screenshot()
  440. return PublishResult(
  441. success=False,
  442. platform=self.platform_name,
  443. error="未找到上传入口",
  444. screenshot_base64=screenshot_base64,
  445. page_url=await self.get_page_url(),
  446. status='failed'
  447. )
  448. self.report_progress(20, "等待视频上传...")
  449. # 等待视频上传完成(最多5分钟)
  450. upload_timeout = 300
  451. start_time = asyncio.get_event_loop().time()
  452. while asyncio.get_event_loop().time() - start_time < upload_timeout:
  453. # 检查上传进度
  454. progress_text = ''
  455. try:
  456. progress_el = self.page.locator('[class*="progress"], [class*="percent"]').first
  457. if await progress_el.count() > 0:
  458. progress_text = await progress_el.text_content()
  459. if progress_text:
  460. import re
  461. match = re.search(r'(\d+)%', progress_text)
  462. if match:
  463. pct = int(match.group(1))
  464. self.report_progress(20 + int(pct * 0.4), f"视频上传中 {pct}%...")
  465. if pct >= 100:
  466. print(f"[{self.platform_name}] 上传完成")
  467. break
  468. except:
  469. pass
  470. # 检查是否出现标题输入框(说明上传完成)
  471. try:
  472. title_input = self.page.locator('input[placeholder*="标题"], textarea[placeholder*="标题"], [class*="title-input"] input').first
  473. if await title_input.count() > 0 and await title_input.is_visible():
  474. print(f"[{self.platform_name}] 检测到标题输入框,上传完成")
  475. break
  476. except:
  477. pass
  478. # 检查是否有错误提示
  479. try:
  480. error_el = self.page.locator('[class*="error"], [class*="fail"]').first
  481. if await error_el.count() > 0:
  482. error_text = await error_el.text_content()
  483. if error_text and ('失败' in error_text or '错误' in error_text):
  484. raise Exception(f"上传失败: {error_text}")
  485. except:
  486. pass
  487. await asyncio.sleep(3)
  488. self.report_progress(60, "正在填写标题...")
  489. await asyncio.sleep(2)
  490. # 填写标题
  491. title_filled = False
  492. title_selectors = [
  493. 'input[placeholder*="标题"]',
  494. 'textarea[placeholder*="标题"]',
  495. '[class*="title-input"] input',
  496. '[class*="title"] input',
  497. 'input[maxlength]',
  498. ]
  499. for selector in title_selectors:
  500. if title_filled:
  501. break
  502. try:
  503. title_input = self.page.locator(selector).first
  504. if await title_input.count() > 0 and await title_input.is_visible():
  505. await title_input.click()
  506. await self.page.keyboard.press("Control+KeyA")
  507. await self.page.keyboard.type(params.title[:30]) # 百家号标题限制30字
  508. title_filled = True
  509. print(f"[{self.platform_name}] 标题填写成功")
  510. except Exception as e:
  511. print(f"[{self.platform_name}] 标题选择器 {selector} 失败: {e}")
  512. if not title_filled:
  513. print(f"[{self.platform_name}] 警告: 未能填写标题")
  514. # 填写描述
  515. if params.description:
  516. self.report_progress(65, "正在填写描述...")
  517. try:
  518. desc_selectors = [
  519. 'textarea[placeholder*="描述"]',
  520. 'textarea[placeholder*="简介"]',
  521. '[class*="desc"] textarea',
  522. '[class*="description"] textarea',
  523. ]
  524. for selector in desc_selectors:
  525. try:
  526. desc_input = self.page.locator(selector).first
  527. if await desc_input.count() > 0 and await desc_input.is_visible():
  528. await desc_input.click()
  529. await self.page.keyboard.type(params.description[:200])
  530. print(f"[{self.platform_name}] 描述填写成功")
  531. break
  532. except:
  533. pass
  534. except Exception as e:
  535. print(f"[{self.platform_name}] 描述填写失败: {e}")
  536. self.report_progress(70, "正在发布...")
  537. await asyncio.sleep(2)
  538. # 点击发布按钮
  539. publish_selectors = [
  540. 'button:has-text("发布")',
  541. 'button:has-text("发表")',
  542. 'button:has-text("提交")',
  543. '[class*="publish"] button',
  544. '[class*="submit"] button',
  545. ]
  546. publish_clicked = False
  547. for selector in publish_selectors:
  548. if publish_clicked:
  549. break
  550. try:
  551. btn = self.page.locator(selector).first
  552. if await btn.count() > 0 and await btn.is_visible():
  553. # 检查按钮是否可用
  554. is_disabled = await btn.get_attribute('disabled')
  555. if is_disabled:
  556. print(f"[{self.platform_name}] 按钮 {selector} 被禁用")
  557. continue
  558. await btn.click()
  559. publish_clicked = True
  560. print(f"[{self.platform_name}] 点击发布按钮成功")
  561. except Exception as e:
  562. print(f"[{self.platform_name}] 发布按钮 {selector} 失败: {e}")
  563. if not publish_clicked:
  564. screenshot_base64 = await self.capture_screenshot()
  565. return PublishResult(
  566. success=False,
  567. platform=self.platform_name,
  568. error="未找到发布按钮",
  569. screenshot_base64=screenshot_base64,
  570. page_url=await self.get_page_url(),
  571. status='failed'
  572. )
  573. self.report_progress(80, "等待发布完成...")
  574. # 记录点击发布前的 URL
  575. publish_page_url = self.page.url
  576. print(f"[{self.platform_name}] 发布前 URL: {publish_page_url}")
  577. # 等待发布完成(最多3分钟)
  578. publish_timeout = 180
  579. start_time = asyncio.get_event_loop().time()
  580. last_url = publish_page_url
  581. while asyncio.get_event_loop().time() - start_time < publish_timeout:
  582. await asyncio.sleep(3)
  583. current_url = self.page.url
  584. # 检测 URL 是否发生变化
  585. if current_url != last_url:
  586. print(f"[{self.platform_name}] URL 变化: {last_url} -> {current_url}")
  587. last_url = current_url
  588. # 检查是否跳转到内容管理页面(真正的成功标志)
  589. # 百家号发布成功后会跳转到 /builder/rc/content 页面
  590. if '/builder/rc/content' in current_url and 'edit' not in current_url:
  591. self.report_progress(100, "发布成功!")
  592. print(f"[{self.platform_name}] 发布成功,已跳转到内容管理页: {current_url}")
  593. screenshot_base64 = await self.capture_screenshot()
  594. return PublishResult(
  595. success=True,
  596. platform=self.platform_name,
  597. message="发布成功",
  598. screenshot_base64=screenshot_base64,
  599. page_url=current_url,
  600. status='success'
  601. )
  602. # 检查是否有明确的成功提示弹窗
  603. try:
  604. # 百家号发布成功会显示"发布成功"弹窗
  605. success_modal = self.page.locator('div:has-text("发布成功"), div:has-text("提交成功"), div:has-text("视频发布成功")').first
  606. if await success_modal.count() > 0 and await success_modal.is_visible():
  607. self.report_progress(100, "发布成功!")
  608. print(f"[{self.platform_name}] 检测到发布成功弹窗")
  609. screenshot_base64 = await self.capture_screenshot()
  610. # 等待一下看是否会跳转
  611. await asyncio.sleep(3)
  612. return PublishResult(
  613. success=True,
  614. platform=self.platform_name,
  615. message="发布成功",
  616. screenshot_base64=screenshot_base64,
  617. page_url=self.page.url,
  618. status='success'
  619. )
  620. except Exception as e:
  621. print(f"[{self.platform_name}] 检测成功提示异常: {e}")
  622. # 检查是否有错误提示
  623. try:
  624. error_selectors = [
  625. 'div.error-tip',
  626. 'div[class*="error-msg"]',
  627. 'span[class*="error"]',
  628. 'div:has-text("发布失败")',
  629. 'div:has-text("提交失败")',
  630. ]
  631. for error_selector in error_selectors:
  632. error_el = self.page.locator(error_selector).first
  633. if await error_el.count() > 0 and await error_el.is_visible():
  634. error_text = await error_el.text_content()
  635. if error_text and error_text.strip():
  636. print(f"[{self.platform_name}] 检测到错误: {error_text}")
  637. screenshot_base64 = await self.capture_screenshot()
  638. return PublishResult(
  639. success=False,
  640. platform=self.platform_name,
  641. error=f"发布失败: {error_text.strip()}",
  642. screenshot_base64=screenshot_base64,
  643. page_url=current_url,
  644. status='failed'
  645. )
  646. except Exception as e:
  647. print(f"[{self.platform_name}] 检测错误提示异常: {e}")
  648. # 检查验证码
  649. captcha_result = await self.check_captcha()
  650. if captcha_result['need_captcha']:
  651. screenshot_base64 = await self.capture_screenshot()
  652. return PublishResult(
  653. success=False,
  654. platform=self.platform_name,
  655. error=f"发布过程中需要{captcha_result['captcha_type']}验证码",
  656. need_captcha=True,
  657. captcha_type=captcha_result['captcha_type'],
  658. screenshot_base64=screenshot_base64,
  659. page_url=current_url,
  660. status='need_captcha'
  661. )
  662. # 检查发布按钮状态(如果还在编辑页面)
  663. if 'edit' in current_url:
  664. try:
  665. # 检查是否正在上传/处理中
  666. processing_indicators = [
  667. '[class*="loading"]',
  668. '[class*="uploading"]',
  669. '[class*="processing"]',
  670. 'div:has-text("正在上传")',
  671. 'div:has-text("正在处理")',
  672. ]
  673. is_processing = False
  674. for indicator in processing_indicators:
  675. if await self.page.locator(indicator).count() > 0:
  676. is_processing = True
  677. print(f"[{self.platform_name}] 正在处理中...")
  678. break
  679. if not is_processing:
  680. # 如果不是在处理中,可能需要重新点击发布按钮
  681. elapsed = asyncio.get_event_loop().time() - start_time
  682. if elapsed > 30: # 30秒后还在编辑页且不在处理中,可能发布没生效
  683. print(f"[{self.platform_name}] 发布似乎未生效,尝试重新点击发布按钮...")
  684. for selector in publish_selectors:
  685. try:
  686. btn = self.page.locator(selector).first
  687. if await btn.count() > 0 and await btn.is_visible():
  688. is_disabled = await btn.get_attribute('disabled')
  689. if not is_disabled:
  690. await btn.click()
  691. print(f"[{self.platform_name}] 重新点击发布按钮")
  692. break
  693. except:
  694. pass
  695. except Exception as e:
  696. print(f"[{self.platform_name}] 检查处理状态异常: {e}")
  697. # 超时,获取截图分析最终状态
  698. print(f"[{self.platform_name}] 发布超时,最终 URL: {self.page.url}")
  699. screenshot_base64 = await self.capture_screenshot()
  700. # 最后一次检查是否在内容管理页
  701. final_url = self.page.url
  702. if '/builder/rc/content' in final_url and 'edit' not in final_url:
  703. return PublishResult(
  704. success=True,
  705. platform=self.platform_name,
  706. message="发布成功(延迟确认)",
  707. screenshot_base64=screenshot_base64,
  708. page_url=final_url,
  709. status='success'
  710. )
  711. return PublishResult(
  712. success=False,
  713. platform=self.platform_name,
  714. error="发布超时,请手动检查发布状态",
  715. screenshot_base64=screenshot_base64,
  716. page_url=final_url,
  717. status='need_action'
  718. )
  719. async def get_works(self, cookies: str, page: int = 0, page_size: int = 20) -> WorksResult:
  720. """
  721. 获取百家号作品列表
  722. 优先使用内容管理页的接口(pcui/article/lists)。
  723. 说明:
  724. - 该接口通常需要自定义请求头 token(JWT),仅靠 Cookie 可能会返回“未登录”
  725. - 这里使用 Playwright 打开内容页,从 localStorage/sessionStorage/页面脚本中自动提取 token,
  726. 再在页面上下文中发起 fetch(携带 cookie + token),以提高成功率
  727. """
  728. import re
  729. print(f"\n{'='*60}")
  730. print(f"[{self.platform_name}] 获取作品列表 (使用 API)")
  731. print(f"[{self.platform_name}] page={page}, page_size={page_size}")
  732. print(f"{'='*60}")
  733. works: List[WorkItem] = []
  734. total = 0
  735. has_more = False
  736. next_page = ""
  737. try:
  738. # 解析并设置 cookies(Playwright)
  739. cookie_list = self.parse_cookies(cookies)
  740. await self.init_browser()
  741. await self.set_cookies(cookie_list)
  742. if not self.page:
  743. raise Exception("Page not initialized")
  744. # 先打开内容管理页,确保本页 Referer/会话就绪
  745. # Node 侧传 page=0,1,...;接口 currentPage 为 1,2,...
  746. current_page = int(page) + 1
  747. page_size = int(page_size)
  748. content_url = (
  749. "https://baijiahao.baidu.com/builder/rc/content"
  750. f"?currentPage={current_page}&pageSize={page_size}"
  751. "&search=&type=&collection=&startDate=&endDate="
  752. )
  753. await self.page.goto(content_url, wait_until="domcontentloaded", timeout=60000)
  754. await asyncio.sleep(2)
  755. # 1) 提取 token(JWT)
  756. token = await self.page.evaluate(
  757. """
  758. () => {
  759. const isJwtLike = (v) => {
  760. if (!v || typeof v !== 'string') return false;
  761. const s = v.trim();
  762. if (s.length < 60) return false;
  763. const parts = s.split('.');
  764. if (parts.length !== 3) return false;
  765. return parts.every(p => /^[A-Za-z0-9_-]+$/.test(p) && p.length > 10);
  766. };
  767. const pickFromStorage = (storage) => {
  768. try {
  769. const keys = Object.keys(storage || {});
  770. for (const k of keys) {
  771. const v = storage.getItem(k);
  772. if (isJwtLike(v)) return v;
  773. }
  774. } catch {}
  775. return "";
  776. };
  777. // localStorage / sessionStorage
  778. let t = pickFromStorage(window.localStorage);
  779. if (t) return t;
  780. t = pickFromStorage(window.sessionStorage);
  781. if (t) return t;
  782. // meta 标签
  783. const meta = document.querySelector('meta[name="token"], meta[name="bjh-token"]');
  784. const metaToken = meta && meta.getAttribute('content');
  785. if (isJwtLike(metaToken)) return metaToken;
  786. // 简单从全局变量里找
  787. const candidates = [
  788. (window.__INITIAL_STATE__ && window.__INITIAL_STATE__.token) || "",
  789. (window.__PRELOADED_STATE__ && window.__PRELOADED_STATE__.token) || "",
  790. (window.__NUXT__ && window.__NUXT__.state && window.__NUXT__.state.token) || "",
  791. ];
  792. for (const c of candidates) {
  793. if (isJwtLike(c)) return c;
  794. }
  795. return "";
  796. }
  797. """
  798. )
  799. # 2) 若仍未取到 token,再从页面 HTML 兜底提取
  800. if not token:
  801. html = await self.page.content()
  802. m = re.search(r'([A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})', html)
  803. if m:
  804. token = m.group(1)
  805. if not token:
  806. raise Exception("未能从页面提取 token(可能未登录或触发风控),请重新登录百家号账号后再试")
  807. # 3) 调用接口(在页面上下文 fetch,自动携带 cookie)
  808. api_url = (
  809. "https://baijiahao.baidu.com/pcui/article/lists"
  810. f"?currentPage={current_page}"
  811. f"&pageSize={page_size}"
  812. "&search=&type=&collection=&startDate=&endDate="
  813. "&clearBeforeFetch=false"
  814. "&dynamic=1"
  815. )
  816. resp = await self.page.evaluate(
  817. """
  818. async ({ url, token }) => {
  819. const r = await fetch(url, {
  820. method: 'GET',
  821. credentials: 'include',
  822. headers: {
  823. 'accept': 'application/json, text/plain, */*',
  824. ...(token ? { token } : {}),
  825. },
  826. });
  827. const text = await r.text();
  828. return { ok: r.ok, status: r.status, text };
  829. }
  830. """,
  831. {"url": api_url, "token": token},
  832. )
  833. if not resp or not resp.get("ok"):
  834. status = resp.get("status") if isinstance(resp, dict) else "unknown"
  835. raise Exception(f"百家号接口请求失败: HTTP {status}")
  836. api_result = json.loads(resp.get("text") or "{}")
  837. print(f"[{self.platform_name}] pcui/article/lists 响应: errno={api_result.get('errno')}, errmsg={api_result.get('errmsg')}")
  838. if api_result.get("errno") != 0:
  839. errno = api_result.get("errno")
  840. errmsg = api_result.get("errmsg", "unknown error")
  841. # 20040001 常见为“未登录”
  842. if errno in (110, 20040001):
  843. raise Exception("百家号未登录或 Cookie/token 失效,请重新登录后再同步")
  844. raise Exception(f"百家号接口错误: errno={errno}, errmsg={errmsg}")
  845. data = api_result.get("data", {}) or {}
  846. items = data.get("list", []) or []
  847. page_info = data.get("page", {}) or {}
  848. total = int(page_info.get("totalCount", 0) or 0)
  849. total_page = int(page_info.get("totalPage", 0) or 0)
  850. cur_page = int(page_info.get("currentPage", current_page) or current_page)
  851. has_more = bool(total_page and cur_page < total_page)
  852. next_page = cur_page + 1 if has_more else ""
  853. print(f"[{self.platform_name}] 获取到 {len(items)} 个作品,总数: {total}, currentPage={cur_page}, totalPage={total_page}")
  854. def _pick_cover(item: dict) -> str:
  855. cover = item.get("crosswise_cover") or item.get("vertical_cover") or ""
  856. if cover:
  857. return cover
  858. raw = item.get("cover_images") or ""
  859. try:
  860. # cover_images 可能是 JSON 字符串
  861. parsed = json.loads(raw) if isinstance(raw, str) else raw
  862. if isinstance(parsed, list) and parsed:
  863. first = parsed[0]
  864. if isinstance(first, dict):
  865. return first.get("src") or first.get("ori_src") or ""
  866. if isinstance(first, str):
  867. return first
  868. except Exception:
  869. pass
  870. return ""
  871. def _pick_duration(item: dict) -> int:
  872. for k in ("rmb_duration", "duration", "long"):
  873. try:
  874. v = int(item.get(k) or 0)
  875. if v > 0:
  876. return v
  877. except Exception:
  878. pass
  879. # displaytype_exinfo 里可能有 ugcvideo.video_info.durationInSecond
  880. ex = item.get("displaytype_exinfo") or ""
  881. try:
  882. exj = json.loads(ex) if isinstance(ex, str) and ex else (ex if isinstance(ex, dict) else {})
  883. ugc = (exj.get("ugcvideo") or {}) if isinstance(exj, dict) else {}
  884. vi = ugc.get("video_info") or {}
  885. v = int(vi.get("durationInSecond") or ugc.get("long") or 0)
  886. return v if v > 0 else 0
  887. except Exception:
  888. return 0
  889. def _pick_status(item: dict) -> str:
  890. qs = str(item.get("quality_status") or "").lower()
  891. st = str(item.get("status") or "").lower()
  892. if qs == "rejected" or "reject" in st:
  893. return "rejected"
  894. if st in ("draft", "unpublish", "unpublished"):
  895. return "draft"
  896. # 百家号常见 publish
  897. return "published"
  898. for item in items:
  899. # 优先使用 nid(builder 预览链接使用这个)
  900. work_id = str(item.get("nid") or item.get("feed_id") or item.get("article_id") or item.get("id") or "")
  901. if not work_id:
  902. continue
  903. works.append(
  904. WorkItem(
  905. work_id=work_id,
  906. title=str(item.get("title") or ""),
  907. cover_url=_pick_cover(item),
  908. video_url=str(item.get("url") or ""),
  909. duration=_pick_duration(item),
  910. status=_pick_status(item),
  911. publish_time=str(item.get("publish_time") or item.get("publish_at") or item.get("created_at") or ""),
  912. play_count=int(item.get("read_amount") or 0),
  913. like_count=int(item.get("like_amount") or 0),
  914. comment_count=int(item.get("comment_amount") or 0),
  915. share_count=int(item.get("share_amount") or 0),
  916. collect_count=int(item.get("collection_amount") or 0),
  917. )
  918. )
  919. print(f"[{self.platform_name}] ✓ 成功解析 {len(works)} 个作品")
  920. except Exception as e:
  921. import traceback
  922. traceback.print_exc()
  923. return WorksResult(
  924. success=False,
  925. platform=self.platform_name,
  926. error=str(e),
  927. debug_info="baijiahao_get_works_failed"
  928. )
  929. return WorksResult(
  930. success=True,
  931. platform=self.platform_name,
  932. works=works,
  933. total=total,
  934. has_more=has_more,
  935. next_page=next_page
  936. )
  937. async def check_login_status(self, cookies: str) -> dict:
  938. """
  939. 检查百家号 Cookie 登录状态
  940. 使用直接 HTTP API 调用,不使用浏览器
  941. """
  942. import aiohttp
  943. print(f"[{self.platform_name}] 检查登录状态 (使用 API)")
  944. try:
  945. # 解析 cookies
  946. cookie_list = self.parse_cookies(cookies)
  947. cookie_dict = {c['name']: c['value'] for c in cookie_list}
  948. # 重要:百家号需要先访问主页建立会话上下文
  949. session_headers = {
  950. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
  951. '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',
  952. # Cookie 由 session 管理
  953. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  954. 'Accept-Encoding': 'gzip, deflate, br',
  955. 'Connection': 'keep-alive',
  956. 'Upgrade-Insecure-Requests': '1',
  957. 'Sec-Fetch-Dest': 'document',
  958. 'Sec-Fetch-Mode': 'navigate',
  959. 'Sec-Fetch-Site': 'none',
  960. 'Sec-Fetch-User': '?1',
  961. 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
  962. 'sec-ch-ua-mobile': '?0',
  963. 'sec-ch-ua-platform': '"Windows"'
  964. }
  965. headers = {
  966. 'Accept': 'application/json, text/plain, */*',
  967. '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',
  968. # Cookie 由 session 管理
  969. 'Referer': 'https://baijiahao.baidu.com/builder/rc/home',
  970. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  971. 'Accept-Encoding': 'gzip, deflate, br',
  972. 'Connection': 'keep-alive',
  973. 'Sec-Fetch-Dest': 'empty',
  974. 'Sec-Fetch-Mode': 'cors',
  975. 'Sec-Fetch-Site': 'same-origin',
  976. 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
  977. 'sec-ch-ua-mobile': '?0',
  978. 'sec-ch-ua-platform': '"Windows"'
  979. }
  980. async with aiohttp.ClientSession(cookies=cookie_dict) as session:
  981. # 步骤 0: 先访问主页建立会话上下文(关键步骤!)
  982. print(f"[{self.platform_name}] [0/2] 访问主页建立会话上下文...")
  983. async with session.get(
  984. 'https://baijiahao.baidu.com/builder/rc/home',
  985. headers=session_headers,
  986. timeout=aiohttp.ClientTimeout(total=30)
  987. ) as home_response:
  988. home_status = home_response.status
  989. print(f"[{self.platform_name}] 主页访问状态: {home_status}")
  990. # 短暂等待确保会话建立
  991. await asyncio.sleep(1)
  992. # 步骤 1: 调用 API 检查登录状态
  993. print(f"[{self.platform_name}] [1/2] 调用 appinfo API 检查登录状态...")
  994. async with session.get(
  995. 'https://baijiahao.baidu.com/builder/app/appinfo',
  996. headers=headers,
  997. timeout=aiohttp.ClientTimeout(total=30)
  998. ) as response:
  999. api_result = await response.json()
  1000. errno = api_result.get('errno')
  1001. print(f"[{self.platform_name}] API 完整响应: {json.dumps(api_result, ensure_ascii=False)[:500]}")
  1002. print(f"[{self.platform_name}] API 响应: errno={errno}")
  1003. # errno 为 0 表示请求成功
  1004. if errno == 0:
  1005. # 检查是否有用户数据
  1006. user_data = api_result.get('data', {}).get('user', {})
  1007. if user_data:
  1008. # 检查账号状态
  1009. status = user_data.get('status', '')
  1010. account_name = user_data.get('name') or user_data.get('uname', '')
  1011. # 有效的账号状态:audit(审核中), pass(已通过), normal(正常), newbie(新手)
  1012. valid_statuses = ['audit', 'pass', 'normal', 'newbie']
  1013. if status in valid_statuses and account_name:
  1014. print(f"[{self.platform_name}] ✓ 登录状态有效: {account_name} (status={status})")
  1015. return {
  1016. "success": True,
  1017. "valid": True,
  1018. "need_login": False,
  1019. "message": "登录状态有效"
  1020. }
  1021. else:
  1022. print(f"[{self.platform_name}] 账号状态异常: status={status}, name={account_name}")
  1023. return {
  1024. "success": True,
  1025. "valid": False,
  1026. "need_login": True,
  1027. "message": f"账号状态异常: {status}"
  1028. }
  1029. else:
  1030. print(f"[{self.platform_name}] 无用户数据,Cookie 可能无效")
  1031. return {
  1032. "success": True,
  1033. "valid": False,
  1034. "need_login": True,
  1035. "message": "无用户数据"
  1036. }
  1037. # errno 非 0 表示请求失败
  1038. # 常见错误码:110 = 未登录
  1039. error_msg = api_result.get('errmsg', '未知错误')
  1040. print(f"[{self.platform_name}] Cookie 无效: errno={errno}, msg={error_msg}")
  1041. return {
  1042. "success": True,
  1043. "valid": False,
  1044. "need_login": True,
  1045. "message": error_msg
  1046. }
  1047. except Exception as e:
  1048. import traceback
  1049. traceback.print_exc()
  1050. return {
  1051. "success": False,
  1052. "valid": False,
  1053. "need_login": True,
  1054. "error": str(e)
  1055. }
  1056. async def get_comments(self, cookies: str, work_id: str, cursor: str = "") -> CommentsResult:
  1057. """获取百家号作品评论"""
  1058. # TODO: 实现评论获取逻辑
  1059. return CommentsResult(
  1060. success=False,
  1061. platform=self.platform_name,
  1062. work_id=work_id,
  1063. error="百家号评论功能暂未实现"
  1064. )