baijiahao.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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_str = '; '.join([f"{c['name']}={c['value']}" for c in cookie_list])
  39. headers = {
  40. 'Accept': 'application/json, text/plain, */*',
  41. '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',
  42. 'Cookie': cookie_str,
  43. 'Referer': 'https://baijiahao.baidu.com/builder/rc/home'
  44. }
  45. async with aiohttp.ClientSession() as session:
  46. # 步骤 1: 获取账号基本信息
  47. print(f"[{self.platform_name}] [1/3] 调用 appinfo API...")
  48. async with session.get(
  49. 'https://baijiahao.baidu.com/builder/app/appinfo',
  50. headers=headers,
  51. timeout=aiohttp.ClientTimeout(total=30)
  52. ) as response:
  53. appinfo_result = await response.json()
  54. print(f"[{self.platform_name}] appinfo API 完整响应: {json.dumps(appinfo_result, ensure_ascii=False)[:500]}")
  55. print(f"[{self.platform_name}] appinfo API 响应: errno={appinfo_result.get('errno')}")
  56. # 检查登录状态
  57. if appinfo_result.get('errno') != 0:
  58. error_msg = appinfo_result.get('errmsg', '未知错误')
  59. errno = appinfo_result.get('errno')
  60. print(f"[{self.platform_name}] API 返回错误: errno={errno}, msg={error_msg}")
  61. # errno 110 表示未登录
  62. if errno == 110:
  63. return {
  64. "success": False,
  65. "error": "Cookie 已失效,需要重新登录",
  66. "need_login": True
  67. }
  68. return {
  69. "success": False,
  70. "error": error_msg,
  71. "need_login": True
  72. }
  73. # 获取用户数据
  74. user_data = appinfo_result.get('data', {}).get('user', {})
  75. if not user_data:
  76. return {
  77. "success": False,
  78. "error": "无法获取用户信息",
  79. "need_login": True
  80. }
  81. # 检查账号状态
  82. status = user_data.get('status', '')
  83. # 有效的账号状态:audit(审核中), pass(已通过), normal(正常), newbie(新手)
  84. valid_statuses = ['audit', 'pass', 'normal', 'newbie']
  85. if status not in valid_statuses:
  86. print(f"[{self.platform_name}] 账号状态异常: {status}")
  87. # 提取基本信息
  88. account_name = user_data.get('name') or user_data.get('uname') or '百家号账号'
  89. app_id = user_data.get('app_id') or user_data.get('id', 0)
  90. account_id = str(app_id) if app_id else f"baijiahao_{int(datetime.now().timestamp() * 1000)}"
  91. # 处理头像 URL
  92. avatar_url = user_data.get('avatar') or user_data.get('avatar_unify', '')
  93. if avatar_url and avatar_url.startswith('//'):
  94. avatar_url = 'https:' + avatar_url
  95. print(f"[{self.platform_name}] 账号名称: {account_name}, ID: {account_id}")
  96. # 步骤 2: 获取粉丝数(非关键,失败不影响整体)
  97. fans_count = 0
  98. try:
  99. print(f"[{self.platform_name}] [2/3] 调用 growth/get_info API 获取粉丝数...")
  100. async with session.get(
  101. 'https://baijiahao.baidu.com/cms-ui/rights/growth/get_info',
  102. headers=headers,
  103. timeout=aiohttp.ClientTimeout(total=10)
  104. ) as response:
  105. growth_result = await response.json()
  106. if growth_result.get('errno') == 0:
  107. growth_data = growth_result.get('data', {})
  108. fans_count = int(growth_data.get('fans_num', 0))
  109. print(f"[{self.platform_name}] 粉丝数: {fans_count}")
  110. else:
  111. print(f"[{self.platform_name}] 获取粉丝数失败: {growth_result.get('errmsg')}")
  112. except Exception as e:
  113. print(f"[{self.platform_name}] 获取粉丝数异常(非关键): {e}")
  114. # 步骤 3: 获取作品数量(从作品列表第一页)
  115. works_count = 0
  116. try:
  117. print(f"[{self.platform_name}] [3/3] 调用 article/lists API 获取作品数...")
  118. async with session.get(
  119. 'https://baijiahao.baidu.com/pcui/article/lists?start=0&count=1&article_type=video',
  120. headers=headers,
  121. timeout=aiohttp.ClientTimeout(total=10)
  122. ) as response:
  123. works_result = await response.json()
  124. if works_result.get('errno') == 0:
  125. works_data = works_result.get('data', {})
  126. works_count = int(works_data.get('total', 0))
  127. print(f"[{self.platform_name}] 作品数: {works_count}")
  128. else:
  129. print(f"[{self.platform_name}] 获取作品数失败: {works_result.get('errmsg')}")
  130. except Exception as e:
  131. print(f"[{self.platform_name}] 获取作品数异常(非关键): {e}")
  132. # 返回账号信息
  133. account_info = {
  134. "success": True,
  135. "account_id": account_id,
  136. "account_name": account_name,
  137. "avatar_url": avatar_url,
  138. "fans_count": fans_count,
  139. "works_count": works_count,
  140. }
  141. print(f"[{self.platform_name}] ✓ 获取成功: {account_name} (粉丝: {fans_count}, 作品: {works_count})")
  142. return account_info
  143. except Exception as e:
  144. import traceback
  145. traceback.print_exc()
  146. return {
  147. "success": False,
  148. "error": str(e)
  149. }
  150. async def check_captcha(self) -> dict:
  151. """检查页面是否需要验证码"""
  152. if not self.page:
  153. return {'need_captcha': False, 'captcha_type': ''}
  154. try:
  155. # 检查各种验证码
  156. captcha_selectors = [
  157. 'text="请输入验证码"',
  158. 'text="滑动验证"',
  159. '[class*="captcha"]',
  160. '[class*="verify"]',
  161. ]
  162. for selector in captcha_selectors:
  163. try:
  164. if await self.page.locator(selector).count() > 0:
  165. print(f"[{self.platform_name}] 检测到验证码: {selector}")
  166. return {'need_captcha': True, 'captcha_type': 'image'}
  167. except:
  168. pass
  169. # 检查登录弹窗
  170. login_selectors = [
  171. 'text="请登录"',
  172. 'text="登录后继续"',
  173. '[class*="login-dialog"]',
  174. ]
  175. for selector in login_selectors:
  176. try:
  177. if await self.page.locator(selector).count() > 0:
  178. print(f"[{self.platform_name}] 检测到需要登录: {selector}")
  179. return {'need_captcha': True, 'captcha_type': 'login'}
  180. except:
  181. pass
  182. except Exception as e:
  183. print(f"[{self.platform_name}] 验证码检测异常: {e}")
  184. return {'need_captcha': False, 'captcha_type': ''}
  185. async def publish(self, cookies: str, params: PublishParams) -> PublishResult:
  186. """发布视频到百家号"""
  187. import os
  188. print(f"\n{'='*60}")
  189. print(f"[{self.platform_name}] 开始发布视频")
  190. print(f"[{self.platform_name}] 视频路径: {params.video_path}")
  191. print(f"[{self.platform_name}] 标题: {params.title}")
  192. print(f"[{self.platform_name}] Headless: {self.headless}")
  193. print(f"{'='*60}")
  194. self.report_progress(5, "正在初始化浏览器...")
  195. # 初始化浏览器
  196. await self.init_browser()
  197. print(f"[{self.platform_name}] 浏览器初始化完成")
  198. # 解析并设置 cookies
  199. cookie_list = self.parse_cookies(cookies)
  200. print(f"[{self.platform_name}] 解析到 {len(cookie_list)} 个 cookies")
  201. await self.set_cookies(cookie_list)
  202. if not self.page:
  203. raise Exception("Page not initialized")
  204. # 检查视频文件
  205. if not os.path.exists(params.video_path):
  206. raise Exception(f"视频文件不存在: {params.video_path}")
  207. print(f"[{self.platform_name}] 视频文件存在,大小: {os.path.getsize(params.video_path)} bytes")
  208. self.report_progress(10, "正在打开上传页面...")
  209. # 访问视频发布页面(使用新视频发布界面)
  210. video_publish_url = "https://baijiahao.baidu.com/builder/rc/edit?type=videoV2&is_from_cms=1"
  211. await self.page.goto(video_publish_url, wait_until="domcontentloaded", timeout=60000)
  212. await asyncio.sleep(3)
  213. # 检查是否跳转到登录页
  214. current_url = self.page.url
  215. print(f"[{self.platform_name}] 当前页面: {current_url}")
  216. for indicator in self.login_indicators:
  217. if indicator in current_url:
  218. screenshot_base64 = await self.capture_screenshot()
  219. return PublishResult(
  220. success=False,
  221. platform=self.platform_name,
  222. error="Cookie 已过期,需要重新登录",
  223. need_captcha=True,
  224. captcha_type='login',
  225. screenshot_base64=screenshot_base64,
  226. page_url=current_url,
  227. status='need_captcha'
  228. )
  229. # 使用 AI 检查验证码
  230. ai_captcha = await self.ai_check_captcha()
  231. if ai_captcha['has_captcha']:
  232. print(f"[{self.platform_name}] AI检测到验证码: {ai_captcha['captcha_type']}", flush=True)
  233. screenshot_base64 = await self.capture_screenshot()
  234. return PublishResult(
  235. success=False,
  236. platform=self.platform_name,
  237. error=f"检测到{ai_captcha['captcha_type']}验证码,需要使用有头浏览器完成验证",
  238. need_captcha=True,
  239. captcha_type=ai_captcha['captcha_type'],
  240. screenshot_base64=screenshot_base64,
  241. page_url=current_url,
  242. status='need_captcha'
  243. )
  244. # 传统方式检查验证码
  245. captcha_result = await self.check_captcha()
  246. if captcha_result['need_captcha']:
  247. screenshot_base64 = await self.capture_screenshot()
  248. return PublishResult(
  249. success=False,
  250. platform=self.platform_name,
  251. error=f"需要{captcha_result['captcha_type']}验证码,请使用有头浏览器完成验证",
  252. need_captcha=True,
  253. captcha_type=captcha_result['captcha_type'],
  254. screenshot_base64=screenshot_base64,
  255. page_url=current_url,
  256. status='need_captcha'
  257. )
  258. self.report_progress(15, "正在选择视频文件...")
  259. # 等待页面加载完成
  260. await asyncio.sleep(2)
  261. # 关闭可能的弹窗
  262. try:
  263. close_buttons = [
  264. 'button:has-text("我知道了")',
  265. 'button:has-text("知道了")',
  266. '[class*="close"]',
  267. '[class*="modal-close"]',
  268. ]
  269. for btn_selector in close_buttons:
  270. try:
  271. btn = self.page.locator(btn_selector).first
  272. if await btn.count() > 0 and await btn.is_visible():
  273. await btn.click()
  274. await asyncio.sleep(0.5)
  275. except:
  276. pass
  277. except:
  278. pass
  279. # 上传视频 - 尝试多种方式
  280. upload_success = False
  281. # 方法1: 直接通过 file input 上传
  282. try:
  283. file_inputs = await self.page.query_selector_all('input[type="file"]')
  284. print(f"[{self.platform_name}] 找到 {len(file_inputs)} 个文件输入")
  285. for file_input in file_inputs:
  286. try:
  287. await file_input.set_input_files(params.video_path)
  288. upload_success = True
  289. print(f"[{self.platform_name}] 通过 file input 上传成功")
  290. break
  291. except Exception as e:
  292. print(f"[{self.platform_name}] file input 上传失败: {e}")
  293. except Exception as e:
  294. print(f"[{self.platform_name}] 查找 file input 失败: {e}")
  295. # 方法2: 点击上传区域
  296. if not upload_success:
  297. upload_selectors = [
  298. 'div[class*="upload-box"]',
  299. 'div[class*="drag-upload"]',
  300. 'div[class*="uploader"]',
  301. 'div:has-text("点击上传")',
  302. 'div:has-text("选择文件")',
  303. '[class*="upload-area"]',
  304. ]
  305. for selector in upload_selectors:
  306. if upload_success:
  307. break
  308. try:
  309. upload_area = self.page.locator(selector).first
  310. if await upload_area.count() > 0:
  311. print(f"[{self.platform_name}] 尝试点击上传区域: {selector}")
  312. async with self.page.expect_file_chooser(timeout=10000) as fc_info:
  313. await upload_area.click()
  314. file_chooser = await fc_info.value
  315. await file_chooser.set_files(params.video_path)
  316. upload_success = True
  317. print(f"[{self.platform_name}] 通过点击上传区域成功")
  318. break
  319. except Exception as e:
  320. print(f"[{self.platform_name}] 选择器 {selector} 失败: {e}")
  321. if not upload_success:
  322. screenshot_base64 = await self.capture_screenshot()
  323. return PublishResult(
  324. success=False,
  325. platform=self.platform_name,
  326. error="未找到上传入口",
  327. screenshot_base64=screenshot_base64,
  328. page_url=await self.get_page_url(),
  329. status='failed'
  330. )
  331. self.report_progress(20, "等待视频上传...")
  332. # 等待视频上传完成(最多5分钟)
  333. upload_timeout = 300
  334. start_time = asyncio.get_event_loop().time()
  335. while asyncio.get_event_loop().time() - start_time < upload_timeout:
  336. # 检查上传进度
  337. progress_text = ''
  338. try:
  339. progress_el = self.page.locator('[class*="progress"], [class*="percent"]').first
  340. if await progress_el.count() > 0:
  341. progress_text = await progress_el.text_content()
  342. if progress_text:
  343. import re
  344. match = re.search(r'(\d+)%', progress_text)
  345. if match:
  346. pct = int(match.group(1))
  347. self.report_progress(20 + int(pct * 0.4), f"视频上传中 {pct}%...")
  348. if pct >= 100:
  349. print(f"[{self.platform_name}] 上传完成")
  350. break
  351. except:
  352. pass
  353. # 检查是否出现标题输入框(说明上传完成)
  354. try:
  355. title_input = self.page.locator('input[placeholder*="标题"], textarea[placeholder*="标题"], [class*="title-input"] input').first
  356. if await title_input.count() > 0 and await title_input.is_visible():
  357. print(f"[{self.platform_name}] 检测到标题输入框,上传完成")
  358. break
  359. except:
  360. pass
  361. # 检查是否有错误提示
  362. try:
  363. error_el = self.page.locator('[class*="error"], [class*="fail"]').first
  364. if await error_el.count() > 0:
  365. error_text = await error_el.text_content()
  366. if error_text and ('失败' in error_text or '错误' in error_text):
  367. raise Exception(f"上传失败: {error_text}")
  368. except:
  369. pass
  370. await asyncio.sleep(3)
  371. self.report_progress(60, "正在填写标题...")
  372. await asyncio.sleep(2)
  373. # 填写标题
  374. title_filled = False
  375. title_selectors = [
  376. 'input[placeholder*="标题"]',
  377. 'textarea[placeholder*="标题"]',
  378. '[class*="title-input"] input',
  379. '[class*="title"] input',
  380. 'input[maxlength]',
  381. ]
  382. for selector in title_selectors:
  383. if title_filled:
  384. break
  385. try:
  386. title_input = self.page.locator(selector).first
  387. if await title_input.count() > 0 and await title_input.is_visible():
  388. await title_input.click()
  389. await self.page.keyboard.press("Control+KeyA")
  390. await self.page.keyboard.type(params.title[:30]) # 百家号标题限制30字
  391. title_filled = True
  392. print(f"[{self.platform_name}] 标题填写成功")
  393. except Exception as e:
  394. print(f"[{self.platform_name}] 标题选择器 {selector} 失败: {e}")
  395. if not title_filled:
  396. print(f"[{self.platform_name}] 警告: 未能填写标题")
  397. # 填写描述
  398. if params.description:
  399. self.report_progress(65, "正在填写描述...")
  400. try:
  401. desc_selectors = [
  402. 'textarea[placeholder*="描述"]',
  403. 'textarea[placeholder*="简介"]',
  404. '[class*="desc"] textarea',
  405. '[class*="description"] textarea',
  406. ]
  407. for selector in desc_selectors:
  408. try:
  409. desc_input = self.page.locator(selector).first
  410. if await desc_input.count() > 0 and await desc_input.is_visible():
  411. await desc_input.click()
  412. await self.page.keyboard.type(params.description[:200])
  413. print(f"[{self.platform_name}] 描述填写成功")
  414. break
  415. except:
  416. pass
  417. except Exception as e:
  418. print(f"[{self.platform_name}] 描述填写失败: {e}")
  419. self.report_progress(70, "正在发布...")
  420. await asyncio.sleep(2)
  421. # 点击发布按钮
  422. publish_selectors = [
  423. 'button:has-text("发布")',
  424. 'button:has-text("发表")',
  425. 'button:has-text("提交")',
  426. '[class*="publish"] button',
  427. '[class*="submit"] button',
  428. ]
  429. publish_clicked = False
  430. for selector in publish_selectors:
  431. if publish_clicked:
  432. break
  433. try:
  434. btn = self.page.locator(selector).first
  435. if await btn.count() > 0 and await btn.is_visible():
  436. # 检查按钮是否可用
  437. is_disabled = await btn.get_attribute('disabled')
  438. if is_disabled:
  439. print(f"[{self.platform_name}] 按钮 {selector} 被禁用")
  440. continue
  441. await btn.click()
  442. publish_clicked = True
  443. print(f"[{self.platform_name}] 点击发布按钮成功")
  444. except Exception as e:
  445. print(f"[{self.platform_name}] 发布按钮 {selector} 失败: {e}")
  446. if not publish_clicked:
  447. screenshot_base64 = await self.capture_screenshot()
  448. return PublishResult(
  449. success=False,
  450. platform=self.platform_name,
  451. error="未找到发布按钮",
  452. screenshot_base64=screenshot_base64,
  453. page_url=await self.get_page_url(),
  454. status='failed'
  455. )
  456. self.report_progress(80, "等待发布完成...")
  457. # 记录点击发布前的 URL
  458. publish_page_url = self.page.url
  459. print(f"[{self.platform_name}] 发布前 URL: {publish_page_url}")
  460. # 等待发布完成(最多3分钟)
  461. publish_timeout = 180
  462. start_time = asyncio.get_event_loop().time()
  463. last_url = publish_page_url
  464. while asyncio.get_event_loop().time() - start_time < publish_timeout:
  465. await asyncio.sleep(3)
  466. current_url = self.page.url
  467. # 检测 URL 是否发生变化
  468. if current_url != last_url:
  469. print(f"[{self.platform_name}] URL 变化: {last_url} -> {current_url}")
  470. last_url = current_url
  471. # 检查是否跳转到内容管理页面(真正的成功标志)
  472. # 百家号发布成功后会跳转到 /builder/rc/content 页面
  473. if '/builder/rc/content' in current_url and 'edit' not in current_url:
  474. self.report_progress(100, "发布成功!")
  475. print(f"[{self.platform_name}] 发布成功,已跳转到内容管理页: {current_url}")
  476. screenshot_base64 = await self.capture_screenshot()
  477. return PublishResult(
  478. success=True,
  479. platform=self.platform_name,
  480. message="发布成功",
  481. screenshot_base64=screenshot_base64,
  482. page_url=current_url,
  483. status='success'
  484. )
  485. # 检查是否有明确的成功提示弹窗
  486. try:
  487. # 百家号发布成功会显示"发布成功"弹窗
  488. success_modal = self.page.locator('div:has-text("发布成功"), div:has-text("提交成功"), div:has-text("视频发布成功")').first
  489. if await success_modal.count() > 0 and await success_modal.is_visible():
  490. self.report_progress(100, "发布成功!")
  491. print(f"[{self.platform_name}] 检测到发布成功弹窗")
  492. screenshot_base64 = await self.capture_screenshot()
  493. # 等待一下看是否会跳转
  494. await asyncio.sleep(3)
  495. return PublishResult(
  496. success=True,
  497. platform=self.platform_name,
  498. message="发布成功",
  499. screenshot_base64=screenshot_base64,
  500. page_url=self.page.url,
  501. status='success'
  502. )
  503. except Exception as e:
  504. print(f"[{self.platform_name}] 检测成功提示异常: {e}")
  505. # 检查是否有错误提示
  506. try:
  507. error_selectors = [
  508. 'div.error-tip',
  509. 'div[class*="error-msg"]',
  510. 'span[class*="error"]',
  511. 'div:has-text("发布失败")',
  512. 'div:has-text("提交失败")',
  513. ]
  514. for error_selector in error_selectors:
  515. error_el = self.page.locator(error_selector).first
  516. if await error_el.count() > 0 and await error_el.is_visible():
  517. error_text = await error_el.text_content()
  518. if error_text and error_text.strip():
  519. print(f"[{self.platform_name}] 检测到错误: {error_text}")
  520. screenshot_base64 = await self.capture_screenshot()
  521. return PublishResult(
  522. success=False,
  523. platform=self.platform_name,
  524. error=f"发布失败: {error_text.strip()}",
  525. screenshot_base64=screenshot_base64,
  526. page_url=current_url,
  527. status='failed'
  528. )
  529. except Exception as e:
  530. print(f"[{self.platform_name}] 检测错误提示异常: {e}")
  531. # 检查验证码
  532. captcha_result = await self.check_captcha()
  533. if captcha_result['need_captcha']:
  534. screenshot_base64 = await self.capture_screenshot()
  535. return PublishResult(
  536. success=False,
  537. platform=self.platform_name,
  538. error=f"发布过程中需要{captcha_result['captcha_type']}验证码",
  539. need_captcha=True,
  540. captcha_type=captcha_result['captcha_type'],
  541. screenshot_base64=screenshot_base64,
  542. page_url=current_url,
  543. status='need_captcha'
  544. )
  545. # 检查发布按钮状态(如果还在编辑页面)
  546. if 'edit' in current_url:
  547. try:
  548. # 检查是否正在上传/处理中
  549. processing_indicators = [
  550. '[class*="loading"]',
  551. '[class*="uploading"]',
  552. '[class*="processing"]',
  553. 'div:has-text("正在上传")',
  554. 'div:has-text("正在处理")',
  555. ]
  556. is_processing = False
  557. for indicator in processing_indicators:
  558. if await self.page.locator(indicator).count() > 0:
  559. is_processing = True
  560. print(f"[{self.platform_name}] 正在处理中...")
  561. break
  562. if not is_processing:
  563. # 如果不是在处理中,可能需要重新点击发布按钮
  564. elapsed = asyncio.get_event_loop().time() - start_time
  565. if elapsed > 30: # 30秒后还在编辑页且不在处理中,可能发布没生效
  566. print(f"[{self.platform_name}] 发布似乎未生效,尝试重新点击发布按钮...")
  567. for selector in publish_selectors:
  568. try:
  569. btn = self.page.locator(selector).first
  570. if await btn.count() > 0 and await btn.is_visible():
  571. is_disabled = await btn.get_attribute('disabled')
  572. if not is_disabled:
  573. await btn.click()
  574. print(f"[{self.platform_name}] 重新点击发布按钮")
  575. break
  576. except:
  577. pass
  578. except Exception as e:
  579. print(f"[{self.platform_name}] 检查处理状态异常: {e}")
  580. # 超时,获取截图分析最终状态
  581. print(f"[{self.platform_name}] 发布超时,最终 URL: {self.page.url}")
  582. screenshot_base64 = await self.capture_screenshot()
  583. # 最后一次检查是否在内容管理页
  584. final_url = self.page.url
  585. if '/builder/rc/content' in final_url and 'edit' not in final_url:
  586. return PublishResult(
  587. success=True,
  588. platform=self.platform_name,
  589. message="发布成功(延迟确认)",
  590. screenshot_base64=screenshot_base64,
  591. page_url=final_url,
  592. status='success'
  593. )
  594. return PublishResult(
  595. success=False,
  596. platform=self.platform_name,
  597. error="发布超时,请手动检查发布状态",
  598. screenshot_base64=screenshot_base64,
  599. page_url=final_url,
  600. status='need_action'
  601. )
  602. async def get_works(self, cookies: str, page: int = 0, page_size: int = 20) -> WorksResult:
  603. """
  604. 获取百家号作品列表
  605. 使用直接 HTTP API 调用,不使用浏览器
  606. """
  607. import aiohttp
  608. print(f"\n{'='*60}")
  609. print(f"[{self.platform_name}] 获取作品列表 (使用 API)")
  610. print(f"[{self.platform_name}] page={page}, page_size={page_size}")
  611. print(f"{'='*60}")
  612. works: List[WorkItem] = []
  613. total = 0
  614. has_more = False
  615. try:
  616. # 解析 cookies
  617. cookie_list = self.parse_cookies(cookies)
  618. cookie_str = '; '.join([f"{c['name']}={c['value']}" for c in cookie_list])
  619. headers = {
  620. 'Accept': 'application/json, text/plain, */*',
  621. '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',
  622. 'Cookie': cookie_str,
  623. 'Referer': 'https://baijiahao.baidu.com/builder/rc/content'
  624. }
  625. # 计算起始位置
  626. start = page * page_size
  627. async with aiohttp.ClientSession() as session:
  628. print(f"[{self.platform_name}] 调用 article/lists API (start={start}, count={page_size})...")
  629. async with session.get(
  630. f'https://baijiahao.baidu.com/pcui/article/lists?start={start}&count={page_size}&article_type=video',
  631. headers=headers,
  632. timeout=aiohttp.ClientTimeout(total=30)
  633. ) as response:
  634. api_result = await response.json()
  635. print(f"[{self.platform_name}] article/lists API 完整响应: {json.dumps(api_result, ensure_ascii=False)[:500]}")
  636. print(f"[{self.platform_name}] API 响应: errno={api_result.get('errno')}")
  637. # 检查登录状态
  638. if api_result.get('errno') != 0:
  639. error_msg = api_result.get('errmsg', '未知错误')
  640. errno = api_result.get('errno')
  641. print(f"[{self.platform_name}] API 返回错误: errno={errno}, msg={error_msg}")
  642. if errno == 110:
  643. raise Exception("Cookie 已过期,请重新登录")
  644. raise Exception(error_msg)
  645. # 解析作品列表
  646. data = api_result.get('data', {})
  647. article_list = data.get('article_list', [])
  648. has_more = data.get('has_more', False)
  649. total = data.get('total', 0)
  650. print(f"[{self.platform_name}] 获取到 {len(article_list)} 个作品,总数: {total}")
  651. for article in article_list:
  652. work_id = str(article.get('article_id', ''))
  653. if not work_id:
  654. continue
  655. # 处理封面图
  656. cover_url = ''
  657. cover_images = article.get('cover_images', [])
  658. if cover_images and len(cover_images) > 0:
  659. cover_url = cover_images[0]
  660. if cover_url and cover_url.startswith('//'):
  661. cover_url = 'https:' + cover_url
  662. works.append(WorkItem(
  663. work_id=work_id,
  664. title=article.get('title', ''),
  665. cover_url=cover_url,
  666. duration=0,
  667. status='published',
  668. publish_time=article.get('publish_time', ''),
  669. play_count=int(article.get('read_count', 0)),
  670. like_count=int(article.get('like_count', 0)),
  671. comment_count=int(article.get('comment_count', 0)),
  672. share_count=int(article.get('share_count', 0)),
  673. ))
  674. print(f"[{self.platform_name}] ✓ 成功解析 {len(works)} 个作品")
  675. except Exception as e:
  676. import traceback
  677. traceback.print_exc()
  678. return WorksResult(
  679. success=False,
  680. platform=self.platform_name,
  681. error=str(e)
  682. )
  683. return WorksResult(
  684. success=True,
  685. platform=self.platform_name,
  686. works=works,
  687. total=total,
  688. has_more=has_more
  689. )
  690. async def check_login_status(self, cookies: str) -> dict:
  691. """
  692. 检查百家号 Cookie 登录状态
  693. 使用直接 HTTP API 调用,不使用浏览器
  694. """
  695. import aiohttp
  696. print(f"[{self.platform_name}] 检查登录状态 (使用 API)")
  697. try:
  698. # 解析 cookies
  699. cookie_list = self.parse_cookies(cookies)
  700. cookie_str = '; '.join([f"{c['name']}={c['value']}" for c in cookie_list])
  701. headers = {
  702. 'Accept': 'application/json, text/plain, */*',
  703. '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',
  704. 'Cookie': cookie_str,
  705. 'Referer': 'https://baijiahao.baidu.com/builder/rc/home'
  706. }
  707. async with aiohttp.ClientSession() as session:
  708. print(f"[{self.platform_name}] 调用 appinfo API 检查登录状态...")
  709. async with session.get(
  710. 'https://baijiahao.baidu.com/builder/app/appinfo',
  711. headers=headers,
  712. timeout=aiohttp.ClientTimeout(total=30)
  713. ) as response:
  714. api_result = await response.json()
  715. errno = api_result.get('errno')
  716. print(f"[{self.platform_name}] API 完整响应: {json.dumps(api_result, ensure_ascii=False)[:500]}")
  717. print(f"[{self.platform_name}] API 响应: errno={errno}")
  718. # errno 为 0 表示请求成功
  719. if errno == 0:
  720. # 检查是否有用户数据
  721. user_data = api_result.get('data', {}).get('user', {})
  722. if user_data:
  723. # 检查账号状态
  724. status = user_data.get('status', '')
  725. account_name = user_data.get('name') or user_data.get('uname', '')
  726. # 有效的账号状态:audit(审核中), pass(已通过), normal(正常), newbie(新手)
  727. valid_statuses = ['audit', 'pass', 'normal', 'newbie']
  728. if status in valid_statuses and account_name:
  729. print(f"[{self.platform_name}] ✓ 登录状态有效: {account_name} (status={status})")
  730. return {
  731. "success": True,
  732. "valid": True,
  733. "need_login": False,
  734. "message": "登录状态有效"
  735. }
  736. else:
  737. print(f"[{self.platform_name}] 账号状态异常: status={status}, name={account_name}")
  738. return {
  739. "success": True,
  740. "valid": False,
  741. "need_login": True,
  742. "message": f"账号状态异常: {status}"
  743. }
  744. else:
  745. print(f"[{self.platform_name}] 无用户数据,Cookie 可能无效")
  746. return {
  747. "success": True,
  748. "valid": False,
  749. "need_login": True,
  750. "message": "无用户数据"
  751. }
  752. # errno 非 0 表示请求失败
  753. # 常见错误码:110 = 未登录
  754. error_msg = api_result.get('errmsg', '未知错误')
  755. print(f"[{self.platform_name}] Cookie 无效: errno={errno}, msg={error_msg}")
  756. return {
  757. "success": True,
  758. "valid": False,
  759. "need_login": True,
  760. "message": error_msg
  761. }
  762. except Exception as e:
  763. import traceback
  764. traceback.print_exc()
  765. return {
  766. "success": False,
  767. "valid": False,
  768. "need_login": True,
  769. "error": str(e)
  770. }
  771. async def get_comments(self, cookies: str, work_id: str, cursor: str = "") -> CommentsResult:
  772. """获取百家号作品评论"""
  773. # TODO: 实现评论获取逻辑
  774. return CommentsResult(
  775. success=False,
  776. platform=self.platform_name,
  777. work_id=work_id,
  778. error="百家号评论功能暂未实现"
  779. )