weixin.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. # -*- coding: utf-8 -*-
  2. """
  3. 微信视频号发布器
  4. 参考: matrix/tencent_uploader/main.py
  5. """
  6. import asyncio
  7. import os
  8. from datetime import datetime
  9. from typing import List
  10. from .base import (
  11. BasePublisher, PublishParams, PublishResult,
  12. WorkItem, WorksResult, CommentItem, CommentsResult
  13. )
  14. def format_short_title(origin_title: str) -> str:
  15. """
  16. 格式化短标题
  17. - 移除特殊字符
  18. - 长度限制在 6-16 字符
  19. """
  20. allowed_special_chars = "《》"":+?%°"
  21. filtered_chars = [
  22. char if char.isalnum() or char in allowed_special_chars
  23. else ' ' if char == ',' else ''
  24. for char in origin_title
  25. ]
  26. formatted_string = ''.join(filtered_chars)
  27. if len(formatted_string) > 16:
  28. formatted_string = formatted_string[:16]
  29. elif len(formatted_string) < 6:
  30. formatted_string += ' ' * (6 - len(formatted_string))
  31. return formatted_string
  32. class WeixinPublisher(BasePublisher):
  33. """
  34. 微信视频号发布器
  35. 使用 Playwright 自动化操作视频号创作者中心
  36. 注意: 需要使用 Chrome 浏览器,否则可能出现 H264 编码错误
  37. """
  38. platform_name = "weixin"
  39. login_url = "https://channels.weixin.qq.com/platform"
  40. publish_url = "https://channels.weixin.qq.com/platform/post/create"
  41. cookie_domain = ".weixin.qq.com"
  42. async def init_browser(self, storage_state: str = None):
  43. """初始化浏览器 - 使用 Chrome 浏览器"""
  44. from playwright.async_api import async_playwright
  45. playwright = await async_playwright().start()
  46. # 使用 Chrome 浏览器,避免 H264 编码问题
  47. self.browser = await playwright.chromium.launch(
  48. headless=self.headless,
  49. channel="chrome"
  50. )
  51. if storage_state and os.path.exists(storage_state):
  52. self.context = await self.browser.new_context(storage_state=storage_state)
  53. else:
  54. self.context = await self.browser.new_context()
  55. self.page = await self.context.new_page()
  56. return self.page
  57. async def set_schedule_time(self, publish_date: datetime):
  58. """设置定时发布"""
  59. if not self.page:
  60. return
  61. print(f"[{self.platform_name}] 设置定时发布...")
  62. # 点击定时选项
  63. label_element = self.page.locator("label").filter(has_text="定时").nth(1)
  64. await label_element.click()
  65. # 选择日期
  66. await self.page.click('input[placeholder="请选择发表时间"]')
  67. publish_month = f"{publish_date.month:02d}"
  68. current_month = f"{publish_month}月"
  69. # 检查月份
  70. page_month = await self.page.inner_text('span.weui-desktop-picker__panel__label:has-text("月")')
  71. if page_month != current_month:
  72. await self.page.click('button.weui-desktop-btn__icon__right')
  73. # 选择日期
  74. elements = await self.page.query_selector_all('table.weui-desktop-picker__table a')
  75. for element in elements:
  76. class_name = await element.evaluate('el => el.className')
  77. if 'weui-desktop-picker__disabled' in class_name:
  78. continue
  79. text = await element.inner_text()
  80. if text.strip() == str(publish_date.day):
  81. await element.click()
  82. break
  83. # 输入时间
  84. await self.page.click('input[placeholder="请选择时间"]')
  85. await self.page.keyboard.press("Control+KeyA")
  86. await self.page.keyboard.type(str(publish_date.hour))
  87. # 点击其他地方确认
  88. await self.page.locator("div.input-editor").click()
  89. async def handle_upload_error(self, video_path: str):
  90. """处理上传错误"""
  91. if not self.page:
  92. return
  93. print(f"[{self.platform_name}] 视频出错了,重新上传中...")
  94. await self.page.locator('div.media-status-content div.tag-inner:has-text("删除")').click()
  95. await self.page.get_by_role('button', name="删除", exact=True).click()
  96. file_input = self.page.locator('input[type="file"]')
  97. await file_input.set_input_files(video_path)
  98. async def add_title_tags(self, params: PublishParams):
  99. """添加标题和话题"""
  100. if not self.page:
  101. return
  102. await self.page.locator("div.input-editor").click()
  103. await self.page.keyboard.type(params.title)
  104. if params.tags:
  105. await self.page.keyboard.press("Enter")
  106. for tag in params.tags:
  107. await self.page.keyboard.type("#" + tag)
  108. await self.page.keyboard.press("Space")
  109. print(f"[{self.platform_name}] 成功添加标题和 {len(params.tags)} 个话题")
  110. async def add_short_title(self):
  111. """添加短标题"""
  112. if not self.page:
  113. return
  114. try:
  115. short_title_element = self.page.get_by_text("短标题", exact=True).locator("..").locator(
  116. "xpath=following-sibling::div").locator('span input[type="text"]')
  117. if await short_title_element.count():
  118. # 获取已有内容作为短标题
  119. pass
  120. except:
  121. pass
  122. async def upload_cover(self, cover_path: str):
  123. """上传封面图"""
  124. if not self.page or not cover_path or not os.path.exists(cover_path):
  125. return
  126. try:
  127. await asyncio.sleep(2)
  128. preview_btn_info = await self.page.locator(
  129. 'div.finder-tag-wrap.btn:has-text("更换封面")').get_attribute('class')
  130. if "disabled" not in preview_btn_info:
  131. await self.page.locator('div.finder-tag-wrap.btn:has-text("更换封面")').click()
  132. await self.page.locator('div.single-cover-uploader-wrap > div.wrap').hover()
  133. # 删除现有封面
  134. if await self.page.locator(".del-wrap > .svg-icon").count():
  135. await self.page.locator(".del-wrap > .svg-icon").click()
  136. # 上传新封面
  137. preview_div = self.page.locator("div.single-cover-uploader-wrap > div.wrap")
  138. async with self.page.expect_file_chooser() as fc_info:
  139. await preview_div.click()
  140. preview_chooser = await fc_info.value
  141. await preview_chooser.set_files(cover_path)
  142. await asyncio.sleep(2)
  143. await self.page.get_by_role("button", name="确定").click()
  144. await asyncio.sleep(1)
  145. await self.page.get_by_role("button", name="确认").click()
  146. print(f"[{self.platform_name}] 封面上传成功")
  147. except Exception as e:
  148. print(f"[{self.platform_name}] 封面上传失败: {e}")
  149. async def publish(self, cookies: str, params: PublishParams) -> PublishResult:
  150. """发布视频到视频号"""
  151. self.report_progress(5, "正在初始化浏览器...")
  152. # 初始化浏览器(使用 Chrome)
  153. await self.init_browser()
  154. # 解析并设置 cookies
  155. cookie_list = self.parse_cookies(cookies)
  156. await self.set_cookies(cookie_list)
  157. if not self.page:
  158. raise Exception("Page not initialized")
  159. # 检查视频文件
  160. if not os.path.exists(params.video_path):
  161. raise Exception(f"视频文件不存在: {params.video_path}")
  162. self.report_progress(10, "正在打开上传页面...")
  163. # 访问上传页面
  164. await self.page.goto(self.publish_url)
  165. await self.page.wait_for_url(self.publish_url, timeout=30000)
  166. self.report_progress(15, "正在选择视频文件...")
  167. # 点击上传区域
  168. upload_div = self.page.locator("div.upload-content")
  169. async with self.page.expect_file_chooser() as fc_info:
  170. await upload_div.click()
  171. file_chooser = await fc_info.value
  172. await file_chooser.set_files(params.video_path)
  173. self.report_progress(20, "正在填充标题和话题...")
  174. # 添加标题和话题
  175. await self.add_title_tags(params)
  176. self.report_progress(30, "等待视频上传完成...")
  177. # 等待上传完成
  178. for _ in range(120):
  179. try:
  180. button_info = await self.page.get_by_role("button", name="发表").get_attribute('class')
  181. if "weui-desktop-btn_disabled" not in button_info:
  182. print(f"[{self.platform_name}] 视频上传完毕")
  183. # 上传封面
  184. self.report_progress(50, "正在上传封面...")
  185. await self.upload_cover(params.cover_path)
  186. break
  187. else:
  188. # 检查上传错误
  189. if await self.page.locator('div.status-msg.error').count():
  190. if await self.page.locator('div.media-status-content div.tag-inner:has-text("删除")').count():
  191. await self.handle_upload_error(params.video_path)
  192. await asyncio.sleep(3)
  193. except:
  194. await asyncio.sleep(3)
  195. self.report_progress(60, "处理视频设置...")
  196. # 添加短标题
  197. try:
  198. short_title_el = self.page.get_by_text("短标题", exact=True).locator("..").locator(
  199. "xpath=following-sibling::div").locator('span input[type="text"]')
  200. if await short_title_el.count():
  201. short_title = format_short_title(params.title)
  202. await short_title_el.fill(short_title)
  203. except:
  204. pass
  205. # 定时发布
  206. if params.publish_date:
  207. self.report_progress(70, "设置定时发布...")
  208. await self.set_schedule_time(params.publish_date)
  209. self.report_progress(80, "正在发布...")
  210. # 点击发布
  211. for _ in range(30):
  212. try:
  213. publish_btn = self.page.locator('div.form-btns button:has-text("发表")')
  214. if await publish_btn.count():
  215. await publish_btn.click()
  216. await self.page.wait_for_url(
  217. "https://channels.weixin.qq.com/platform/post/list",
  218. timeout=10000
  219. )
  220. self.report_progress(100, "发布成功")
  221. return PublishResult(
  222. success=True,
  223. platform=self.platform_name,
  224. message="发布成功"
  225. )
  226. except:
  227. current_url = self.page.url
  228. if "post/list" in current_url:
  229. self.report_progress(100, "发布成功")
  230. return PublishResult(
  231. success=True,
  232. platform=self.platform_name,
  233. message="发布成功"
  234. )
  235. await asyncio.sleep(1)
  236. raise Exception("发布超时")
  237. async def get_works(self, cookies: str, page: int = 0, page_size: int = 20) -> WorksResult:
  238. """获取视频号作品列表"""
  239. print(f"\n{'='*60}")
  240. print(f"[{self.platform_name}] 获取作品列表")
  241. print(f"[{self.platform_name}] page={page}, page_size={page_size}")
  242. print(f"{'='*60}")
  243. works: List[WorkItem] = []
  244. total = 0
  245. has_more = False
  246. try:
  247. await self.init_browser()
  248. cookie_list = self.parse_cookies(cookies)
  249. await self.set_cookies(cookie_list)
  250. if not self.page:
  251. raise Exception("Page not initialized")
  252. # 访问视频号创作者中心
  253. await self.page.goto("https://channels.weixin.qq.com/platform/post/list")
  254. await asyncio.sleep(5)
  255. # 检查登录状态
  256. current_url = self.page.url
  257. if "login" in current_url:
  258. raise Exception("Cookie 已过期,请重新登录")
  259. # 视频号使用页面爬取方式获取作品列表
  260. # 等待作品列表加载
  261. await self.page.wait_for_selector('div.post-feed-wrap', timeout=10000)
  262. # 获取所有作品项
  263. post_items = self.page.locator('div.post-feed-item')
  264. item_count = await post_items.count()
  265. print(f"[{self.platform_name}] 找到 {item_count} 个作品项")
  266. for i in range(min(item_count, page_size)):
  267. try:
  268. item = post_items.nth(i)
  269. # 获取封面
  270. cover_el = item.locator('div.cover-wrap img').first
  271. cover_url = ''
  272. if await cover_el.count() > 0:
  273. cover_url = await cover_el.get_attribute('src') or ''
  274. # 获取标题
  275. title_el = item.locator('div.content').first
  276. title = ''
  277. if await title_el.count() > 0:
  278. title = await title_el.text_content() or ''
  279. title = title.strip()[:50]
  280. # 获取统计数据
  281. stats_el = item.locator('div.post-data')
  282. play_count = 0
  283. like_count = 0
  284. comment_count = 0
  285. if await stats_el.count() > 0:
  286. stats_text = await stats_el.text_content() or ''
  287. # 解析统计数据(格式可能是: 播放 100 点赞 50 评论 10)
  288. import re
  289. play_match = re.search(r'播放[\s]*([\d.]+[万]?)', stats_text)
  290. like_match = re.search(r'点赞[\s]*([\d.]+[万]?)', stats_text)
  291. comment_match = re.search(r'评论[\s]*([\d.]+[万]?)', stats_text)
  292. def parse_count(match):
  293. if not match:
  294. return 0
  295. val = match.group(1)
  296. if '万' in val:
  297. return int(float(val.replace('万', '')) * 10000)
  298. return int(val)
  299. play_count = parse_count(play_match)
  300. like_count = parse_count(like_match)
  301. comment_count = parse_count(comment_match)
  302. # 获取发布时间
  303. time_el = item.locator('div.time')
  304. publish_time = ''
  305. if await time_el.count() > 0:
  306. publish_time = await time_el.text_content() or ''
  307. publish_time = publish_time.strip()
  308. # 生成临时 work_id(视频号可能需要从详情页获取)
  309. work_id = f"weixin_{i}_{hash(title)}"
  310. works.append(WorkItem(
  311. work_id=work_id,
  312. title=title or '无标题',
  313. cover_url=cover_url,
  314. duration=0,
  315. status='published',
  316. publish_time=publish_time,
  317. play_count=play_count,
  318. like_count=like_count,
  319. comment_count=comment_count,
  320. ))
  321. except Exception as e:
  322. print(f"[{self.platform_name}] 解析作品 {i} 失败: {e}")
  323. continue
  324. total = len(works)
  325. has_more = item_count > page_size
  326. print(f"[{self.platform_name}] 获取到 {total} 个作品")
  327. except Exception as e:
  328. import traceback
  329. traceback.print_exc()
  330. return WorksResult(success=False, platform=self.platform_name, error=str(e))
  331. return WorksResult(success=True, platform=self.platform_name, works=works, total=total, has_more=has_more)
  332. async def get_comments(self, cookies: str, work_id: str, cursor: str = "") -> CommentsResult:
  333. """获取视频号作品评论"""
  334. print(f"\n{'='*60}")
  335. print(f"[{self.platform_name}] 获取作品评论")
  336. print(f"[{self.platform_name}] work_id={work_id}")
  337. print(f"{'='*60}")
  338. comments: List[CommentItem] = []
  339. total = 0
  340. has_more = False
  341. try:
  342. await self.init_browser()
  343. cookie_list = self.parse_cookies(cookies)
  344. await self.set_cookies(cookie_list)
  345. if not self.page:
  346. raise Exception("Page not initialized")
  347. # 访问评论管理页面
  348. await self.page.goto("https://channels.weixin.qq.com/platform/comment/index")
  349. await asyncio.sleep(5)
  350. # 检查登录状态
  351. current_url = self.page.url
  352. if "login" in current_url:
  353. raise Exception("Cookie 已过期,请重新登录")
  354. # 等待评论列表加载
  355. try:
  356. await self.page.wait_for_selector('div.comment-list', timeout=10000)
  357. except:
  358. print(f"[{self.platform_name}] 未找到评论列表")
  359. return CommentsResult(success=True, platform=self.platform_name, work_id=work_id, comments=[], total=0, has_more=False)
  360. # 获取所有评论项
  361. comment_items = self.page.locator('div.comment-item')
  362. item_count = await comment_items.count()
  363. print(f"[{self.platform_name}] 找到 {item_count} 个评论项")
  364. for i in range(item_count):
  365. try:
  366. item = comment_items.nth(i)
  367. # 获取作者信息
  368. author_name = ''
  369. author_avatar = ''
  370. name_el = item.locator('div.nick-name')
  371. if await name_el.count() > 0:
  372. author_name = await name_el.text_content() or ''
  373. author_name = author_name.strip()
  374. avatar_el = item.locator('img.avatar')
  375. if await avatar_el.count() > 0:
  376. author_avatar = await avatar_el.get_attribute('src') or ''
  377. # 获取评论内容
  378. content = ''
  379. content_el = item.locator('div.comment-content')
  380. if await content_el.count() > 0:
  381. content = await content_el.text_content() or ''
  382. content = content.strip()
  383. # 获取时间
  384. create_time = ''
  385. time_el = item.locator('div.time')
  386. if await time_el.count() > 0:
  387. create_time = await time_el.text_content() or ''
  388. create_time = create_time.strip()
  389. # 生成评论 ID
  390. comment_id = f"weixin_comment_{i}_{hash(content)}"
  391. comments.append(CommentItem(
  392. comment_id=comment_id,
  393. work_id=work_id,
  394. content=content,
  395. author_id='',
  396. author_name=author_name,
  397. author_avatar=author_avatar,
  398. like_count=0,
  399. reply_count=0,
  400. create_time=create_time,
  401. ))
  402. except Exception as e:
  403. print(f"[{self.platform_name}] 解析评论 {i} 失败: {e}")
  404. continue
  405. total = len(comments)
  406. print(f"[{self.platform_name}] 获取到 {total} 条评论")
  407. except Exception as e:
  408. import traceback
  409. traceback.print_exc()
  410. return CommentsResult(success=False, platform=self.platform_name, work_id=work_id, error=str(e))
  411. return CommentsResult(success=True, platform=self.platform_name, work_id=work_id, comments=comments, total=total, has_more=has_more)