weixin.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  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. import os
  15. import time
  16. # 允许通过环境变量手动指定“上传视频入口”的选择器,便于在页面结构频繁变更时快速调整
  17. WEIXIN_UPLOAD_SELECTOR = os.environ.get("WEIXIN_UPLOAD_SELECTOR", "").strip()
  18. def format_short_title(origin_title: str) -> str:
  19. """
  20. 格式化短标题
  21. - 移除特殊字符
  22. - 长度限制在 6-16 字符
  23. """
  24. allowed_special_chars = "《》"":+?%°"
  25. filtered_chars = [
  26. char if char.isalnum() or char in allowed_special_chars
  27. else ' ' if char == ',' else ''
  28. for char in origin_title
  29. ]
  30. formatted_string = ''.join(filtered_chars)
  31. if len(formatted_string) > 16:
  32. formatted_string = formatted_string[:16]
  33. elif len(formatted_string) < 6:
  34. formatted_string += ' ' * (6 - len(formatted_string))
  35. return formatted_string
  36. class WeixinPublisher(BasePublisher):
  37. """
  38. 微信视频号发布器
  39. 使用 Playwright 自动化操作视频号创作者中心
  40. 注意: 需要使用 Chrome 浏览器,否则可能出现 H264 编码错误
  41. """
  42. platform_name = "weixin"
  43. login_url = "https://channels.weixin.qq.com/platform"
  44. publish_url = "https://channels.weixin.qq.com/platform/post/create"
  45. cookie_domain = ".weixin.qq.com"
  46. def _parse_count(self, count_str: str) -> int:
  47. """解析数字(支持带'万'的格式)"""
  48. try:
  49. count_str = count_str.strip()
  50. if '万' in count_str:
  51. return int(float(count_str.replace('万', '')) * 10000)
  52. return int(count_str)
  53. except:
  54. return 0
  55. async def ai_find_upload_selector(self, frame_html: str, frame_name: str = "main") -> str:
  56. """
  57. 使用 AI 从 HTML 中识别“上传视频/选择文件”相关元素的 CSS 选择器。
  58. 设计思路:
  59. - 仅在常规 DOM 选择器都失败时调用,避免频繁占用 AI 配额;
  60. - 通过 DashScope 文本模型(与验证码识别同一套配置)分析 HTML;
  61. - 返回一个适合用于 frame.locator(selector) 的 CSS 选择器。
  62. """
  63. import json
  64. import re
  65. import requests
  66. import os
  67. # 避免 HTML 过长导致 token 超限,只截取前 N 字符
  68. if not frame_html:
  69. return ""
  70. max_len = 20000
  71. if len(frame_html) > max_len:
  72. frame_html = frame_html[:max_len]
  73. ai_api_key = os.environ.get("DASHSCOPE_API_KEY", "")
  74. ai_base_url = os.environ.get("DASHSCOPE_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1")
  75. ai_text_model = os.environ.get("AI_TEXT_MODEL", "qwen-plus")
  76. if not ai_api_key:
  77. print(f"[{self.platform_name}] AI上传入口识别: 未配置 AI API Key,跳过")
  78. return ""
  79. prompt = f"""
  80. 你是熟悉微信视频号后台的前端工程师,现在需要在一段 HTML 中找到“上传视频文件”的入口。
  81. 页面说明:
  82. - 平台:微信视频号(channels.weixin.qq.com)
  83. - 目标:用于上传视频文件的按钮或 input(一般会触发文件选择框)
  84. - 你会收到某个 frame 的完整 HTML 片段(不包含截图)。
  85. 请你根据下面的 HTML,推断最适合用于上传视频文件的元素,并输出一个可以被 Playwright 使用的 CSS 选择器。
  86. 要求:
  87. 1. 只考虑“上传/选择视频文件”的入口,不要返回“发布/发表/下一步”等按钮;
  88. 2. 选择器需要尽量稳定,不要使用自动生成的随机类名(例如带很多随机字母/数字的类名可以用前缀匹配);
  89. 3. 选择器必须是 CSS 选择器(不要返回 XPath);
  90. 4. 如果确实找不到合理的上传入口,返回 selector 为空字符串。
  91. 请以 JSON 格式输出,严格遵守以下结构(不要添加任何解释文字):
  92. ```json
  93. {{
  94. "selector": "CSS 选择器字符串,比如:input[type='file'] 或 div.upload-content input[type='file']"
  95. }}
  96. ```
  97. 下面是 frame=\"{frame_name}\" 的 HTML:
  98. ```html
  99. {frame_html}
  100. ```"""
  101. payload = {
  102. "model": ai_text_model,
  103. "messages": [
  104. {
  105. "role": "user",
  106. "content": prompt,
  107. }
  108. ],
  109. "max_tokens": 600,
  110. }
  111. headers = {
  112. "Authorization": f"Bearer {ai_api_key}",
  113. "Content-Type": "application/json",
  114. }
  115. try:
  116. print(f"[{self.platform_name}] AI上传入口识别: 正在分析 frame={frame_name} HTML...")
  117. resp = requests.post(
  118. f"{ai_base_url}/chat/completions",
  119. headers=headers,
  120. json=payload,
  121. timeout=40,
  122. )
  123. if resp.status_code != 200:
  124. print(f"[{self.platform_name}] AI上传入口识别: API 返回错误 {resp.status_code}")
  125. return ""
  126. data = resp.json()
  127. content = data.get("choices", [{}])[0].get("message", {}).get("content", "") or ""
  128. # 尝试从 ```json``` 代码块中解析
  129. json_match = re.search(r"```json\\s*([\\s\\S]*?)\\s*```", content)
  130. if json_match:
  131. json_str = json_match.group(1)
  132. else:
  133. json_match = re.search(r"\\{[\\s\\S]*\\}", content)
  134. json_str = json_match.group(0) if json_match else "{}"
  135. try:
  136. result = json.loads(json_str)
  137. except Exception:
  138. result = {}
  139. selector = (result.get("selector") or "").strip()
  140. print(f"[{self.platform_name}] AI上传入口识别结果: selector='{selector}'")
  141. return selector
  142. except Exception as e:
  143. print(f"[{self.platform_name}] AI上传入口识别异常: {e}")
  144. return ""
  145. async def ai_pick_selector_from_candidates(self, candidates: list, goal: str, frame_name: str = "main") -> str:
  146. """
  147. 将“候选元素列表(包含 css selector + 文本/属性)”发给 AI,让 AI 直接挑选最符合 goal 的元素。
  148. 适用于:HTML 里看不出上传入口、或页面大量动态渲染时。
  149. """
  150. import json
  151. import re
  152. import requests
  153. import os
  154. if not candidates:
  155. return ""
  156. ai_api_key = os.environ.get("DASHSCOPE_API_KEY", "")
  157. ai_base_url = os.environ.get("DASHSCOPE_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1")
  158. ai_text_model = os.environ.get("AI_TEXT_MODEL", "qwen-plus")
  159. if not ai_api_key:
  160. print(f"[{self.platform_name}] AI候选选择器: 未配置 AI API Key,跳过")
  161. return ""
  162. # 控制长度,最多取前 120 个候选
  163. candidates = candidates[:120]
  164. prompt = f"""
  165. 你是自动化发布工程师。现在要在微信视频号(channels.weixin.qq.com)发布页面里找到“{goal}”相关的入口元素。
  166. 我会给你一组候选元素,每个候选都包含:
  167. - css: 可直接用于 Playwright 的 CSS 选择器
  168. - tag / type / role / ariaLabel / text / id / className(部分字段可能为空)
  169. 你的任务:
  170. - 从候选中选出最可能用于“{goal}”的元素,返回它的 css 选择器;
  171. - 如果没有任何候选符合,返回空字符串。
  172. 注意:
  173. - 如果 goal 是“上传视频入口”,优先选择 input[type=file] 或看起来会触发选择文件/上传的区域;
  174. - 不要选择“发布/发表/下一步”等按钮(除非 goal 明确是发布按钮)。
  175. 请严格按 JSON 输出(不要解释):
  176. ```json
  177. {{ "selector": "..." }}
  178. ```
  179. 候选列表(frame={frame_name}):
  180. ```json
  181. {json.dumps(candidates, ensure_ascii=False)}
  182. ```"""
  183. payload = {
  184. "model": ai_text_model,
  185. "messages": [{"role": "user", "content": prompt}],
  186. "max_tokens": 400,
  187. }
  188. headers = {
  189. "Authorization": f"Bearer {ai_api_key}",
  190. "Content-Type": "application/json",
  191. }
  192. try:
  193. print(f"[{self.platform_name}] AI候选选择器: 正在分析 frame={frame_name}, goal={goal} ...")
  194. resp = requests.post(
  195. f"{ai_base_url}/chat/completions",
  196. headers=headers,
  197. json=payload,
  198. timeout=40,
  199. )
  200. if resp.status_code != 200:
  201. print(f"[{self.platform_name}] AI候选选择器: API 返回错误 {resp.status_code}")
  202. return ""
  203. data = resp.json()
  204. content = data.get("choices", [{}])[0].get("message", {}).get("content", "") or ""
  205. json_match = re.search(r"```json\\s*([\\s\\S]*?)\\s*```", content)
  206. if json_match:
  207. json_str = json_match.group(1)
  208. else:
  209. json_match = re.search(r"\\{[\\s\\S]*\\}", content)
  210. json_str = json_match.group(0) if json_match else "{}"
  211. try:
  212. result = json.loads(json_str)
  213. except Exception:
  214. result = {}
  215. selector = (result.get("selector") or "").strip()
  216. print(f"[{self.platform_name}] AI候选选择器结果: selector='{selector}'")
  217. return selector
  218. except Exception as e:
  219. print(f"[{self.platform_name}] AI候选选择器异常: {e}")
  220. return ""
  221. async def _extract_relevant_html_snippets(self, html: str) -> str:
  222. """
  223. 从 HTML 中抽取与上传相关的片段,减少 token,提升 AI 命中率。
  224. - 优先抓取包含 upload/上传/file/input 等关键词的窗口片段
  225. - 若未命中关键词,返回“开头 + 结尾”的拼接
  226. """
  227. import re
  228. if not html:
  229. return ""
  230. patterns = [
  231. r"upload",
  232. r"uploader",
  233. r"file",
  234. r"type\\s*=\\s*['\\\"]file['\\\"]",
  235. r"input",
  236. r"drag",
  237. r"drop",
  238. r"选择",
  239. r"上传",
  240. r"添加",
  241. r"视频",
  242. ]
  243. regex = re.compile("|".join(patterns), re.IGNORECASE)
  244. snippets = []
  245. for m in regex.finditer(html):
  246. start = max(0, m.start() - 350)
  247. end = min(len(html), m.end() + 350)
  248. snippets.append(html[start:end])
  249. if len(snippets) >= 18:
  250. break
  251. if snippets:
  252. # 去重(粗略)
  253. unique = []
  254. seen = set()
  255. for s in snippets:
  256. key = hash(s)
  257. if key not in seen:
  258. seen.add(key)
  259. unique.append(s)
  260. return "\n\n<!-- SNIPPET -->\n\n".join(unique)[:20000]
  261. # fallback: head + tail
  262. head = html[:9000]
  263. tail = html[-9000:] if len(html) > 9000 else ""
  264. return (head + "\n\n<!-- TAIL -->\n\n" + tail)[:20000]
  265. async def init_browser(self, storage_state: str = None):
  266. """初始化浏览器 - 参考 matrix 使用 channel=chrome 避免 H264 编码错误"""
  267. from playwright.async_api import async_playwright
  268. playwright = await async_playwright().start()
  269. # 参考 matrix: 使用系统内的 Chrome 浏览器,避免 H264 编码错误
  270. # 如果没有安装 Chrome,则使用默认 Chromium
  271. try:
  272. self.browser = await playwright.chromium.launch(
  273. headless=self.headless,
  274. channel="chrome" # 使用系统 Chrome
  275. )
  276. print(f"[{self.platform_name}] 使用系统 Chrome 浏览器")
  277. except Exception as e:
  278. print(f"[{self.platform_name}] Chrome 不可用,使用 Chromium: {e}")
  279. self.browser = await playwright.chromium.launch(headless=self.headless)
  280. # 设置 HTTP Headers 防止重定向
  281. headers = {
  282. "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
  283. "Referer": "https://channels.weixin.qq.com/platform/post/list",
  284. }
  285. self.context = await self.browser.new_context(
  286. extra_http_headers=headers,
  287. ignore_https_errors=True,
  288. viewport={"width": 1920, "height": 1080},
  289. 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"
  290. )
  291. self.page = await self.context.new_page()
  292. return self.page
  293. async def set_schedule_time(self, publish_date: datetime):
  294. """设置定时发布"""
  295. if not self.page:
  296. return
  297. print(f"[{self.platform_name}] 设置定时发布...")
  298. # 点击定时选项
  299. label_element = self.page.locator("label").filter(has_text="定时").nth(1)
  300. await label_element.click()
  301. # 选择日期
  302. await self.page.click('input[placeholder="请选择发表时间"]')
  303. publish_month = f"{publish_date.month:02d}"
  304. current_month = f"{publish_month}月"
  305. # 检查月份
  306. page_month = await self.page.inner_text('span.weui-desktop-picker__panel__label:has-text("月")')
  307. if page_month != current_month:
  308. await self.page.click('button.weui-desktop-btn__icon__right')
  309. # 选择日期
  310. elements = await self.page.query_selector_all('table.weui-desktop-picker__table a')
  311. for element in elements:
  312. class_name = await element.evaluate('el => el.className')
  313. if 'weui-desktop-picker__disabled' in class_name:
  314. continue
  315. text = await element.inner_text()
  316. if text.strip() == str(publish_date.day):
  317. await element.click()
  318. break
  319. # 输入时间
  320. await self.page.click('input[placeholder="请选择时间"]')
  321. await self.page.keyboard.press("Control+KeyA")
  322. await self.page.keyboard.type(str(publish_date.hour))
  323. # 点击其他地方确认
  324. await self.page.locator("div.input-editor").click()
  325. async def handle_upload_error(self, video_path: str):
  326. """处理上传错误"""
  327. if not self.page:
  328. return
  329. print(f"[{self.platform_name}] 视频出错了,重新上传中...")
  330. await self.page.locator('div.media-status-content div.tag-inner:has-text("删除")').click()
  331. await self.page.get_by_role('button', name="删除", exact=True).click()
  332. file_input = self.page.locator('input[type="file"]')
  333. await file_input.set_input_files(video_path)
  334. async def add_title_tags(self, params: PublishParams):
  335. """添加标题和话题"""
  336. if not self.page:
  337. return
  338. await self.page.locator("div.input-editor").click()
  339. await self.page.keyboard.type(params.title)
  340. if params.tags:
  341. await self.page.keyboard.press("Enter")
  342. for tag in params.tags:
  343. await self.page.keyboard.type("#" + tag)
  344. await self.page.keyboard.press("Space")
  345. print(f"[{self.platform_name}] 成功添加标题和 {len(params.tags)} 个话题")
  346. async def add_short_title(self):
  347. """添加短标题"""
  348. if not self.page:
  349. return
  350. try:
  351. short_title_element = self.page.get_by_text("短标题", exact=True).locator("..").locator(
  352. "xpath=following-sibling::div").locator('span input[type="text"]')
  353. if await short_title_element.count():
  354. # 获取已有内容作为短标题
  355. pass
  356. except:
  357. pass
  358. async def upload_cover(self, cover_path: str):
  359. """上传封面图"""
  360. if not self.page or not cover_path or not os.path.exists(cover_path):
  361. return
  362. try:
  363. await asyncio.sleep(2)
  364. preview_btn_info = await self.page.locator(
  365. 'div.finder-tag-wrap.btn:has-text("更换封面")').get_attribute('class')
  366. if "disabled" not in preview_btn_info:
  367. await self.page.locator('div.finder-tag-wrap.btn:has-text("更换封面")').click()
  368. await self.page.locator('div.single-cover-uploader-wrap > div.wrap').hover()
  369. # 删除现有封面
  370. if await self.page.locator(".del-wrap > .svg-icon").count():
  371. await self.page.locator(".del-wrap > .svg-icon").click()
  372. # 上传新封面
  373. preview_div = self.page.locator("div.single-cover-uploader-wrap > div.wrap")
  374. async with self.page.expect_file_chooser() as fc_info:
  375. await preview_div.click()
  376. preview_chooser = await fc_info.value
  377. await preview_chooser.set_files(cover_path)
  378. await asyncio.sleep(2)
  379. await self.page.get_by_role("button", name="确定").click()
  380. await asyncio.sleep(1)
  381. await self.page.get_by_role("button", name="确认").click()
  382. print(f"[{self.platform_name}] 封面上传成功")
  383. except Exception as e:
  384. print(f"[{self.platform_name}] 封面上传失败: {e}")
  385. async def check_captcha(self) -> dict:
  386. """检查页面是否需要验证码"""
  387. if not self.page:
  388. return {'need_captcha': False, 'captcha_type': ''}
  389. try:
  390. # 检查各种验证码
  391. captcha_selectors = [
  392. 'text="请输入验证码"',
  393. 'text="滑动验证"',
  394. '[class*="captcha"]',
  395. '[class*="verify"]',
  396. ]
  397. for selector in captcha_selectors:
  398. try:
  399. if await self.page.locator(selector).count() > 0:
  400. print(f"[{self.platform_name}] 检测到验证码: {selector}")
  401. return {'need_captcha': True, 'captcha_type': 'image'}
  402. except:
  403. pass
  404. # 检查登录弹窗
  405. login_selectors = [
  406. 'text="请登录"',
  407. 'text="扫码登录"',
  408. '[class*="login-dialog"]',
  409. ]
  410. for selector in login_selectors:
  411. try:
  412. if await self.page.locator(selector).count() > 0:
  413. print(f"[{self.platform_name}] 检测到需要登录: {selector}")
  414. return {'need_captcha': True, 'captcha_type': 'login'}
  415. except:
  416. pass
  417. except Exception as e:
  418. print(f"[{self.platform_name}] 验证码检测异常: {e}")
  419. return {'need_captcha': False, 'captcha_type': ''}
  420. async def publish(self, cookies: str, params: PublishParams) -> PublishResult:
  421. """发布视频到视频号"""
  422. print(f"\n{'='*60}")
  423. print(f"[{self.platform_name}] 开始发布视频")
  424. print(f"[{self.platform_name}] 视频路径: {params.video_path}")
  425. print(f"[{self.platform_name}] 标题: {params.title}")
  426. print(f"[{self.platform_name}] Headless: {self.headless}")
  427. print(f"{'='*60}")
  428. self.report_progress(5, "正在初始化浏览器...")
  429. # 初始化浏览器(使用 Chrome)
  430. await self.init_browser()
  431. print(f"[{self.platform_name}] 浏览器初始化完成")
  432. # 解析并设置 cookies
  433. cookie_list = self.parse_cookies(cookies)
  434. print(cookie_list)
  435. print(f"[{self.platform_name}] 解析到 {len(cookie_list)} 个 cookies")
  436. await self.set_cookies(cookie_list)
  437. if not self.page:
  438. raise Exception("Page not initialized")
  439. # 检查视频文件
  440. if not os.path.exists(params.video_path):
  441. raise Exception(f"视频文件不存在: {params.video_path}")
  442. print(f"[{self.platform_name}] 视频文件存在,大小: {os.path.getsize(params.video_path)} bytes")
  443. self.report_progress(10, "正在打开上传页面...")
  444. # 访问上传页面
  445. await self.page.goto(self.publish_url, wait_until="networkidle", timeout=60000)
  446. await asyncio.sleep(3)
  447. # 检查是否跳转到登录页
  448. current_url = self.page.url
  449. print(f"[{self.platform_name}] 当前页面: {current_url}")
  450. if "login" in current_url:
  451. screenshot_base64 = await self.capture_screenshot()
  452. return PublishResult(
  453. success=False,
  454. platform=self.platform_name,
  455. error="Cookie 已过期,需要重新登录",
  456. need_captcha=True,
  457. captcha_type='login',
  458. screenshot_base64=screenshot_base64,
  459. page_url=current_url,
  460. status='need_captcha'
  461. )
  462. # 使用 AI 检查验证码
  463. ai_captcha = await self.ai_check_captcha()
  464. if ai_captcha['has_captcha']:
  465. print(f"[{self.platform_name}] AI检测到验证码: {ai_captcha['captcha_type']}", flush=True)
  466. screenshot_base64 = await self.capture_screenshot()
  467. return PublishResult(
  468. success=False,
  469. platform=self.platform_name,
  470. error=f"检测到{ai_captcha['captcha_type']}验证码,需要使用有头浏览器完成验证",
  471. need_captcha=True,
  472. captcha_type=ai_captcha['captcha_type'],
  473. screenshot_base64=screenshot_base64,
  474. page_url=current_url,
  475. status='need_captcha'
  476. )
  477. # 传统方式检查验证码
  478. captcha_result = await self.check_captcha()
  479. if captcha_result['need_captcha']:
  480. screenshot_base64 = await self.capture_screenshot()
  481. return PublishResult(
  482. success=False,
  483. platform=self.platform_name,
  484. error=f"需要{captcha_result['captcha_type']}验证码,请使用有头浏览器完成验证",
  485. need_captcha=True,
  486. captcha_type=captcha_result['captcha_type'],
  487. screenshot_base64=screenshot_base64,
  488. page_url=current_url,
  489. status='need_captcha'
  490. )
  491. self.report_progress(15, "正在选择视频文件...")
  492. # 上传视频
  493. # 说明:视频号发布页在不同账号/地区/灰度下 DOM 结构差异较大,且上传组件可能在 iframe 中。
  494. # 因此这里按 matrix 的思路“点击触发 file chooser”,同时增加“遍历全部 frame + 精确挑选 video input”的兜底。
  495. upload_success = False
  496. if not self.page:
  497. raise Exception("Page not initialized")
  498. # 等待页面把上传区域渲染出来(避免过早判断)
  499. try:
  500. await self.page.wait_for_selector("div.upload-content, input[type='file'], iframe", timeout=20000)
  501. except Exception:
  502. pass
  503. async def _try_set_files_in_frame(frame, frame_name: str) -> bool:
  504. """在指定 frame 中尝试触发上传"""
  505. nonlocal upload_success
  506. if upload_success:
  507. return True
  508. # 方法0:如果用户通过环境变量显式配置了选择器,优先尝试这个
  509. if WEIXIN_UPLOAD_SELECTOR:
  510. try:
  511. el = frame.locator(WEIXIN_UPLOAD_SELECTOR).first
  512. if await el.count() > 0 and await el.is_visible():
  513. print(f"[{self.platform_name}] [{frame_name}] 使用环境变量 WEIXIN_UPLOAD_SELECTOR: {WEIXIN_UPLOAD_SELECTOR}")
  514. try:
  515. async with self.page.expect_file_chooser(timeout=5000) as fc_info:
  516. await el.click()
  517. chooser = await fc_info.value
  518. await chooser.set_files(params.video_path)
  519. upload_success = True
  520. print(f"[{self.platform_name}] [{frame_name}] 通过环境变量选择器上传成功")
  521. return True
  522. except Exception as e:
  523. print(f"[{self.platform_name}] [{frame_name}] 环境变量选择器点击失败,尝试直接 set_input_files: {e}")
  524. try:
  525. await el.set_input_files(params.video_path)
  526. upload_success = True
  527. print(f"[{self.platform_name}] [{frame_name}] 环境变量选择器 set_input_files 成功")
  528. return True
  529. except Exception as e2:
  530. print(f"[{self.platform_name}] [{frame_name}] 环境变量选择器 set_input_files 仍失败: {e2}")
  531. except Exception as e:
  532. print(f"[{self.platform_name}] [{frame_name}] 使用环境变量选择器定位元素失败: {e}")
  533. # 先尝试点击上传区域触发 chooser(最贴近 matrix)
  534. click_selectors = [
  535. "div.upload-content",
  536. "div[class*='upload-content']",
  537. "div[class*='upload']",
  538. "div.add-wrap",
  539. "[class*='uploader']",
  540. "text=点击上传",
  541. "text=上传视频",
  542. "text=选择视频",
  543. ]
  544. for selector in click_selectors:
  545. try:
  546. el = frame.locator(selector).first
  547. if await el.count() > 0 and await el.is_visible():
  548. print(f"[{self.platform_name}] [{frame_name}] 找到可点击上传区域: {selector}")
  549. try:
  550. async with self.page.expect_file_chooser(timeout=5000) as fc_info:
  551. await el.click()
  552. chooser = await fc_info.value
  553. await chooser.set_files(params.video_path)
  554. upload_success = True
  555. print(f"[{self.platform_name}] [{frame_name}] 通过 file chooser 上传成功")
  556. return True
  557. except Exception as e:
  558. print(f"[{self.platform_name}] [{frame_name}] 点击触发 chooser 失败: {e}")
  559. except Exception:
  560. pass
  561. # 再尝试直接设置 input[type=file](iframe/隐藏 input 常见)
  562. try:
  563. inputs = frame.locator("input[type='file']")
  564. cnt = await inputs.count()
  565. if cnt > 0:
  566. best_idx = 0
  567. best_score = -1
  568. for i in range(cnt):
  569. try:
  570. inp = inputs.nth(i)
  571. accept = (await inp.get_attribute("accept")) or ""
  572. multiple = (await inp.get_attribute("multiple")) or ""
  573. score = 0
  574. if "video" in accept:
  575. score += 10
  576. if "mp4" in accept:
  577. score += 3
  578. if multiple:
  579. score += 1
  580. if score > best_score:
  581. best_score = score
  582. best_idx = i
  583. except Exception:
  584. continue
  585. target = inputs.nth(best_idx)
  586. print(f"[{self.platform_name}] [{frame_name}] 尝试对 input[{best_idx}] set_input_files (score={best_score})")
  587. await target.set_input_files(params.video_path)
  588. upload_success = True
  589. print(f"[{self.platform_name}] [{frame_name}] 通过 file input 上传成功")
  590. return True
  591. except Exception as e:
  592. print(f"[{self.platform_name}] [{frame_name}] file input 上传失败: {e}")
  593. # 不直接返回,让后面的 AI 兜底有机会执行
  594. # 方法4: 兜底使用 AI 分析 HTML,猜测上传入口
  595. try:
  596. frame_url = getattr(frame, "url", "")
  597. html_full = await frame.content()
  598. html_for_ai = await self._extract_relevant_html_snippets(html_full)
  599. print(f"[{self.platform_name}] [{frame_name}] frame_url={frame_url}, html_len={len(html_full)}, html_for_ai_len={len(html_for_ai)}")
  600. ai_selector = await self.ai_find_upload_selector(html_for_ai, frame_name=frame_name)
  601. if ai_selector:
  602. try:
  603. el = frame.locator(ai_selector).first
  604. if await el.count() > 0:
  605. print(f"[{self.platform_name}] [{frame_name}] 使用 AI 选择器点击上传入口: {ai_selector}")
  606. try:
  607. async with self.page.expect_file_chooser(timeout=5000) as fc_info:
  608. await el.click()
  609. chooser = await fc_info.value
  610. await chooser.set_files(params.video_path)
  611. upload_success = True
  612. print(f"[{self.platform_name}] [{frame_name}] 通过 AI 选择器上传成功")
  613. return True
  614. except Exception as e:
  615. print(f"[{self.platform_name}] [{frame_name}] AI 选择器点击失败,改为直接 set_input_files: {e}")
  616. try:
  617. await el.set_input_files(params.video_path)
  618. upload_success = True
  619. print(f"[{self.platform_name}] [{frame_name}] AI 选择器直接 set_input_files 成功")
  620. return True
  621. except Exception as e2:
  622. print(f"[{self.platform_name}] [{frame_name}] AI 选择器 set_input_files 仍失败: {e2}")
  623. except Exception as e:
  624. print(f"[{self.platform_name}] [{frame_name}] 使用 AI 选择器定位元素失败: {e}")
  625. else:
  626. # 如果 AI 无法从 HTML 推断,退一步:构造候选元素列表交给 AI 选择
  627. try:
  628. candidates = await frame.evaluate("""
  629. () => {
  630. function cssEscape(s) {
  631. try { return CSS.escape(s); } catch (e) { return s.replace(/[^a-zA-Z0-9_-]/g, '\\\\$&'); }
  632. }
  633. function buildSelector(el) {
  634. if (!el || el.nodeType !== 1) return '';
  635. if (el.id) return `#${cssEscape(el.id)}`;
  636. let parts = [];
  637. let cur = el;
  638. for (let depth = 0; cur && cur.nodeType === 1 && depth < 5; depth++) {
  639. let part = cur.tagName.toLowerCase();
  640. const role = cur.getAttribute('role');
  641. const type = cur.getAttribute('type');
  642. if (type) part += `[type="${type}"]`;
  643. if (role) part += `[role="${role}"]`;
  644. const cls = (cur.className || '').toString().trim().split(/\\s+/).filter(Boolean);
  645. if (cls.length) part += '.' + cls.slice(0, 2).map(cssEscape).join('.');
  646. // nth-of-type
  647. let idx = 1;
  648. let sib = cur;
  649. while (sib && (sib = sib.previousElementSibling)) {
  650. if (sib.tagName === cur.tagName) idx++;
  651. }
  652. part += `:nth-of-type(${idx})`;
  653. parts.unshift(part);
  654. cur = cur.parentElement;
  655. }
  656. return parts.join(' > ');
  657. }
  658. const nodes = Array.from(document.querySelectorAll('input, button, a, div, span'))
  659. .filter(el => {
  660. const tag = el.tagName.toLowerCase();
  661. const type = (el.getAttribute('type') || '').toLowerCase();
  662. const role = (el.getAttribute('role') || '').toLowerCase();
  663. const aria = (el.getAttribute('aria-label') || '').toLowerCase();
  664. const txt = (el.innerText || '').trim().slice(0, 60);
  665. const cls = (el.className || '').toString().toLowerCase();
  666. const isFile = tag === 'input' && type === 'file';
  667. const looksClickable =
  668. tag === 'button' || tag === 'a' || role === 'button' || el.onclick ||
  669. cls.includes('upload') || cls.includes('uploader') || cls.includes('drag') ||
  670. aria.includes('上传') || aria.includes('选择') || aria.includes('添加') ||
  671. txt.includes('上传') || txt.includes('选择') || txt.includes('添加') || txt.includes('点击上传');
  672. if (!isFile && !looksClickable) return false;
  673. const r = el.getBoundingClientRect();
  674. const visible = r.width > 5 && r.height > 5;
  675. return visible;
  676. });
  677. const limited = nodes.slice(0, 120).map(el => ({
  678. css: buildSelector(el),
  679. tag: el.tagName.toLowerCase(),
  680. type: el.getAttribute('type') || '',
  681. role: el.getAttribute('role') || '',
  682. ariaLabel: el.getAttribute('aria-label') || '',
  683. text: (el.innerText || '').trim().slice(0, 80),
  684. id: el.id || '',
  685. className: (el.className || '').toString().slice(0, 120),
  686. accept: el.getAttribute('accept') || '',
  687. }));
  688. return limited;
  689. }
  690. """)
  691. ai_selector2 = await self.ai_pick_selector_from_candidates(
  692. candidates=candidates,
  693. goal="上传视频入口",
  694. frame_name=frame_name
  695. )
  696. if ai_selector2:
  697. el2 = frame.locator(ai_selector2).first
  698. if await el2.count() > 0:
  699. print(f"[{self.platform_name}] [{frame_name}] 使用 AI 候选选择器点击上传入口: {ai_selector2}")
  700. try:
  701. async with self.page.expect_file_chooser(timeout=5000) as fc_info:
  702. await el2.click()
  703. chooser2 = await fc_info.value
  704. await chooser2.set_files(params.video_path)
  705. upload_success = True
  706. print(f"[{self.platform_name}] [{frame_name}] 通过 AI 候选选择器上传成功")
  707. return True
  708. except Exception as e:
  709. print(f"[{self.platform_name}] [{frame_name}] AI 候选选择器点击失败,尝试 set_input_files: {e}")
  710. try:
  711. await el2.set_input_files(params.video_path)
  712. upload_success = True
  713. print(f"[{self.platform_name}] [{frame_name}] AI 候选选择器 set_input_files 成功")
  714. return True
  715. except Exception as e2:
  716. print(f"[{self.platform_name}] [{frame_name}] AI 候选选择器 set_input_files 仍失败: {e2}")
  717. except Exception as e:
  718. print(f"[{self.platform_name}] [{frame_name}] 构造候选并交给 AI 失败: {e}")
  719. except Exception as e:
  720. print(f"[{self.platform_name}] [{frame_name}] AI 上传入口识别整体失败: {e}")
  721. return False
  722. # 先尝试主 frame
  723. try:
  724. await _try_set_files_in_frame(self.page.main_frame, "main")
  725. except Exception as e:
  726. print(f"[{self.platform_name}] main frame 上传尝试异常: {e}")
  727. # 再遍历所有子 frame
  728. if not upload_success:
  729. try:
  730. frames = self.page.frames
  731. print(f"[{self.platform_name}] 发现 frames: {len(frames)}")
  732. for idx, fr in enumerate(frames):
  733. if upload_success:
  734. break
  735. # main_frame 已尝试过
  736. if fr == self.page.main_frame:
  737. continue
  738. name = fr.name or f"frame-{idx}"
  739. await _try_set_files_in_frame(fr, name)
  740. except Exception as e:
  741. print(f"[{self.platform_name}] 遍历 frames 异常: {e}")
  742. if not upload_success:
  743. screenshot_base64 = await self.capture_screenshot()
  744. return PublishResult(
  745. success=False,
  746. platform=self.platform_name,
  747. error="未找到上传入口(可能在 iframe 中或页面结构已变更)",
  748. screenshot_base64=screenshot_base64,
  749. page_url=await self.get_page_url(),
  750. status='failed'
  751. )
  752. self.report_progress(20, "正在填充标题和话题...")
  753. # 添加标题和话题
  754. await self.add_title_tags(params)
  755. self.report_progress(30, "等待视频上传完成...")
  756. # 等待上传完成
  757. for _ in range(120):
  758. try:
  759. button_info = await self.page.get_by_role("button", name="发表").get_attribute('class')
  760. if "weui-desktop-btn_disabled" not in button_info:
  761. print(f"[{self.platform_name}] 视频上传完毕")
  762. # 上传封面
  763. self.report_progress(50, "正在上传封面...")
  764. await self.upload_cover(params.cover_path)
  765. break
  766. else:
  767. # 检查上传错误
  768. if await self.page.locator('div.status-msg.error').count():
  769. if await self.page.locator('div.media-status-content div.tag-inner:has-text("删除")').count():
  770. await self.handle_upload_error(params.video_path)
  771. await asyncio.sleep(3)
  772. except:
  773. await asyncio.sleep(3)
  774. self.report_progress(60, "处理视频设置...")
  775. # 添加短标题
  776. try:
  777. short_title_el = self.page.get_by_text("短标题", exact=True).locator("..").locator(
  778. "xpath=following-sibling::div").locator('span input[type="text"]')
  779. if await short_title_el.count():
  780. short_title = format_short_title(params.title)
  781. await short_title_el.fill(short_title)
  782. except:
  783. pass
  784. # 定时发布
  785. if params.publish_date:
  786. self.report_progress(70, "设置定时发布...")
  787. await self.set_schedule_time(params.publish_date)
  788. self.report_progress(80, "正在发布...")
  789. # 点击发布 - 参考 matrix
  790. for i in range(30):
  791. try:
  792. # 参考 matrix: div.form-btns button:has-text("发表")
  793. publish_btn = self.page.locator('div.form-btns button:has-text("发表")')
  794. if await publish_btn.count():
  795. print(f"[{self.platform_name}] 点击发布按钮...")
  796. await publish_btn.click()
  797. # 等待跳转到作品列表页面 - 参考 matrix
  798. await self.page.wait_for_url(
  799. "https://channels.weixin.qq.com/platform/post/list",
  800. timeout=10000
  801. )
  802. self.report_progress(100, "发布成功")
  803. print(f"[{self.platform_name}] 视频发布成功!")
  804. screenshot_base64 = await self.capture_screenshot()
  805. return PublishResult(
  806. success=True,
  807. platform=self.platform_name,
  808. message="发布成功",
  809. screenshot_base64=screenshot_base64,
  810. page_url=self.page.url,
  811. status='success'
  812. )
  813. except Exception as e:
  814. current_url = self.page.url
  815. if "https://channels.weixin.qq.com/platform/post/list" in current_url:
  816. self.report_progress(100, "发布成功")
  817. print(f"[{self.platform_name}] 视频发布成功!")
  818. screenshot_base64 = await self.capture_screenshot()
  819. return PublishResult(
  820. success=True,
  821. platform=self.platform_name,
  822. message="发布成功",
  823. screenshot_base64=screenshot_base64,
  824. page_url=current_url,
  825. status='success'
  826. )
  827. else:
  828. print(f"[{self.platform_name}] 视频正在发布中... {i+1}/30, URL: {current_url}")
  829. await asyncio.sleep(1)
  830. # 发布超时
  831. screenshot_base64 = await self.capture_screenshot()
  832. page_url = await self.get_page_url()
  833. return PublishResult(
  834. success=False,
  835. platform=self.platform_name,
  836. error="发布超时,请检查发布状态",
  837. screenshot_base64=screenshot_base64,
  838. page_url=page_url,
  839. status='need_action'
  840. )
  841. async def get_works(self, cookies: str, page: int = 0, page_size: int = 20) -> WorksResult:
  842. print(f"1111111111111111111")
  843. """获取视频号作品列表"""
  844. print(f"\n{'='*60}")
  845. print(f"[{self.platform_name}] 获取作品列表")
  846. print(f"[{self.platform_name}] page={page}, page_size={page_size}")
  847. print(f"{'='*60}")
  848. works: List[WorkItem] = []
  849. total = 0
  850. has_more = False
  851. try:
  852. await self.init_browser()
  853. cookie_list = self.parse_cookies(cookies)
  854. await self.set_cookies(cookie_list)
  855. if not self.page:
  856. raise Exception("Page not initialized")
  857. # 访问视频号创作者中心
  858. await self.page.goto("https://channels.weixin.qq.com/platform/post/list")
  859. await asyncio.sleep(5)
  860. print(f"1111111111111111")
  861. # 检查登录状态
  862. current_url = self.page.url
  863. if "login" in current_url:
  864. print(f"2111111111111111")
  865. raise Exception("Cookie 已过期,请重新登录")
  866. # 视频号使用页面爬取方式获取作品列表
  867. # 等待作品列表加载(增加等待时间,并添加截图调试)
  868. try:
  869. await self.page.wait_for_selector('div.post-feed-item', timeout=15000)
  870. except:
  871. # 超时后打印当前 URL 和截图
  872. current_url = self.page.url
  873. print(f"[{self.platform_name}] 等待超时,当前 URL: {current_url}")
  874. # 截图保存
  875. screenshot_path = f"weixin_timeout_{int(asyncio.get_event_loop().time())}.png"
  876. await self.page.screenshot(path=screenshot_path)
  877. print(f"[{self.platform_name}] 截图已保存: {screenshot_path}")
  878. raise Exception(f"页面加载超时,当前 URL: {current_url}")
  879. # 打印 DOM 结构
  880. page_html = await self.page.content()
  881. print(f"[{self.platform_name}] ========== 页面 DOM 开始 ==========")
  882. print(page_html[:5000]) # 打印前5000个字符
  883. print(f"[{self.platform_name}] ========== 页面 DOM 结束 ==========")
  884. # 获取所有作品项
  885. post_items = self.page.locator('div.post-feed-item')
  886. item_count = await post_items.count()
  887. print(f"[{self.platform_name}] 找到 {item_count} 个作品项")
  888. for i in range(min(item_count, page_size)):
  889. try:
  890. item = post_items.nth(i)
  891. # 获取封面
  892. cover_el = item.locator('div.media img.thumb').first
  893. cover_url = ''
  894. if await cover_el.count() > 0:
  895. cover_url = await cover_el.get_attribute('src') or ''
  896. # 获取标题
  897. title_el = item.locator('div.post-title').first
  898. title = ''
  899. if await title_el.count() > 0:
  900. title = await title_el.text_content() or ''
  901. title = title.strip()
  902. # 获取发布时间
  903. time_el = item.locator('div.post-time span').first
  904. publish_time = ''
  905. if await time_el.count() > 0:
  906. publish_time = await time_el.text_content() or ''
  907. publish_time = publish_time.strip()
  908. # 获取统计数据
  909. import re
  910. data_items = item.locator('div.post-data div.data-item')
  911. data_count = await data_items.count()
  912. play_count = 0
  913. like_count = 0
  914. comment_count = 0
  915. share_count = 0
  916. collect_count = 0
  917. for j in range(data_count):
  918. data_item = data_items.nth(j)
  919. count_text = await data_item.locator('span.count').text_content() or '0'
  920. count_text = count_text.strip()
  921. # 判断图标类型
  922. if await data_item.locator('span.weui-icon-outlined-eyes-on').count() > 0:
  923. # 播放量
  924. play_count = self._parse_count(count_text)
  925. elif await data_item.locator('span.weui-icon-outlined-like').count() > 0:
  926. # 点赞
  927. like_count = self._parse_count(count_text)
  928. elif await data_item.locator('span.weui-icon-outlined-comment').count() > 0:
  929. # 评论
  930. comment_count = self._parse_count(count_text)
  931. elif await data_item.locator('use[xlink\\:href="#icon-share"]').count() > 0:
  932. # 分享
  933. share_count = self._parse_count(count_text)
  934. elif await data_item.locator('use[xlink\\:href="#icon-thumb"]').count() > 0:
  935. # 收藏
  936. collect_count = self._parse_count(count_text)
  937. # 生成临时 work_id
  938. work_id = f"weixin_{i}_{hash(title)}_{hash(publish_time)}"
  939. works.append(WorkItem(
  940. work_id=work_id,
  941. title=title or '无标题',
  942. cover_url=cover_url,
  943. duration=0,
  944. status='published',
  945. publish_time=publish_time,
  946. play_count=play_count,
  947. like_count=like_count,
  948. comment_count=comment_count,
  949. share_count=share_count,
  950. collect_count=collect_count,
  951. ))
  952. except Exception as e:
  953. print(f"[{self.platform_name}] 解析作品 {i} 失败: {e}")
  954. import traceback
  955. traceback.print_exc()
  956. continue
  957. total = len(works)
  958. has_more = item_count > page_size
  959. print(f"[{self.platform_name}] 获取到 {total} 个作品")
  960. except Exception as e:
  961. import traceback
  962. traceback.print_exc()
  963. return WorksResult(success=False, platform=self.platform_name, error=str(e))
  964. return WorksResult(success=True, platform=self.platform_name, works=works, total=total, has_more=has_more)
  965. async def get_comments(self, cookies: str, work_id: str, cursor: str = "") -> CommentsResult:
  966. """获取视频号作品评论"""
  967. print(f"\n{'='*60}")
  968. print(f"[{self.platform_name}] 获取作品评论")
  969. print(f"[{self.platform_name}] work_id={work_id}")
  970. print(f"{'='*60}")
  971. comments: List[CommentItem] = []
  972. total = 0
  973. has_more = False
  974. try:
  975. await self.init_browser()
  976. cookie_list = self.parse_cookies(cookies)
  977. await self.set_cookies(cookie_list)
  978. if not self.page:
  979. raise Exception("Page not initialized")
  980. # 访问评论管理页面
  981. await self.page.goto("https://channels.weixin.qq.com/platform/interaction/comment")
  982. await asyncio.sleep(3)
  983. # 检查登录状态
  984. current_url = self.page.url
  985. if "login" in current_url:
  986. raise Exception("Cookie 已过期,请重新登录")
  987. # 等待左侧作品列表加载
  988. try:
  989. await self.page.wait_for_selector('div.comment-feed-wrap', timeout=15000)
  990. except:
  991. print(f"[{self.platform_name}] 未找到作品列表")
  992. return CommentsResult(success=True, platform=self.platform_name, work_id=work_id, comments=[], total=0, has_more=False)
  993. print(f"[{self.platform_name}] 查找 work_id={work_id} 对应的作品")
  994. # 点击左侧作品项(根据 work_id 匹配)
  995. feed_items = self.page.locator('div.comment-feed-wrap')
  996. item_count = await feed_items.count()
  997. print(f"[{self.platform_name}] 左侧共 {item_count} 个作品")
  998. clicked = False
  999. for i in range(item_count):
  1000. feed = feed_items.nth(i)
  1001. title_el = feed.locator('div.feed-title').first
  1002. if await title_el.count() > 0:
  1003. title_text = await title_el.text_content() or ''
  1004. title_text = title_text.strip()
  1005. # 检查是否包含 work_id(标题)
  1006. if work_id in title_text or title_text in work_id:
  1007. print(f"[{self.platform_name}] 找到匹配作品: {title_text}")
  1008. await feed.click()
  1009. await asyncio.sleep(2)
  1010. clicked = True
  1011. break
  1012. if not clicked:
  1013. # 如果没找到匹配的,点击第一个
  1014. print(f"[{self.platform_name}] 未找到匹配作品,点击第一个")
  1015. if item_count > 0:
  1016. await feed_items.nth(0).click()
  1017. await asyncio.sleep(2)
  1018. else:
  1019. return CommentsResult(success=True, platform=self.platform_name, work_id=work_id, comments=[], total=0, has_more=False)
  1020. # 等待右侧评论详情加载
  1021. try:
  1022. await self.page.wait_for_selector('div.comment-item', timeout=5000)
  1023. except:
  1024. print(f"[{self.platform_name}] 该作品暂无评论")
  1025. return CommentsResult(success=True, platform=self.platform_name, work_id=work_id, comments=[], total=0, has_more=False)
  1026. # 获取评论总数
  1027. total_text_el = self.page.locator('div.comment-count__tips')
  1028. if await total_text_el.count() > 0:
  1029. total_text = await total_text_el.text_content() or ''
  1030. # 提取数字(如 "共 1 条评论")
  1031. import re
  1032. match = re.search(r'(\d+)', total_text)
  1033. if match:
  1034. total = int(match.group(1))
  1035. print(f"[{self.platform_name}] 评论总数: {total}")
  1036. # 获取右侧评论列表
  1037. comment_items = self.page.locator('div.comment-item')
  1038. item_count = await comment_items.count()
  1039. print(f"[{self.platform_name}] 当前加载 {item_count} 条评论")
  1040. for i in range(item_count):
  1041. try:
  1042. item = comment_items.nth(i)
  1043. # 获取作者昵称(加 .first 防 strict mode)
  1044. author_name = ''
  1045. name_el = item.locator('span.comment-user-name').first
  1046. if await name_el.count() > 0:
  1047. author_name = await name_el.text_content() or ''
  1048. author_name = author_name.strip()
  1049. # 获取头像
  1050. author_avatar = ''
  1051. avatar_el = item.locator('img.comment-avatar').first
  1052. if await avatar_el.count() > 0:
  1053. author_avatar = await avatar_el.get_attribute('src') or ''
  1054. # 获取评论内容(加 .first 防 strict mode)
  1055. content = ''
  1056. content_el = item.locator('span.comment-content').first
  1057. if await content_el.count() > 0:
  1058. content = await content_el.text_content() or ''
  1059. content = content.strip()
  1060. # 获取评论时间(加 .first 防 strict mode)
  1061. create_time = ''
  1062. time_el = item.locator('span.comment-time').first
  1063. if await time_el.count() > 0:
  1064. create_time = await time_el.text_content() or ''
  1065. create_time = create_time.strip()
  1066. if not content:
  1067. continue
  1068. # 生成评论 ID
  1069. comment_id = f"weixin_comment_{i}_{abs(hash(content))}"
  1070. comments.append(CommentItem(
  1071. comment_id=comment_id,
  1072. work_id=work_id,
  1073. content=content,
  1074. author_id='',
  1075. author_name=author_name,
  1076. author_avatar=author_avatar,
  1077. like_count=0,
  1078. reply_count=0,
  1079. create_time=create_time,
  1080. ))
  1081. print(f"[{self.platform_name}] 评论 {i+1}: {author_name} - {content[:20]}...")
  1082. except Exception as e:
  1083. print(f"[{self.platform_name}] 解析评论 {i} 失败: {e}")
  1084. continue
  1085. print(f"[{self.platform_name}] 成功获取 {len(comments)} 条评论")
  1086. except Exception as e:
  1087. import traceback
  1088. traceback.print_exc()
  1089. return CommentsResult(success=False, platform=self.platform_name, work_id=work_id, error=str(e))
  1090. return CommentsResult(success=True, platform=self.platform_name, work_id=work_id, comments=comments, total=total, has_more=has_more)
  1091. async def auto_reply_private_messages(self, cookies: str) -> dict:
  1092. """自动回复私信 - 集成自 pw3.py"""
  1093. print(f"\n{'='*60}")
  1094. print(f"[{self.platform_name}] 开始自动回复私信")
  1095. print(f"{'='*60}")
  1096. try:
  1097. await self.init_browser()
  1098. cookie_list = self.parse_cookies(cookies)
  1099. await self.set_cookies(cookie_list)
  1100. if not self.page:
  1101. raise Exception("Page not initialized")
  1102. # 访问私信页面
  1103. await self.page.goto("https://channels.weixin.qq.com/platform/private_msg", timeout=30000)
  1104. await asyncio.sleep(3)
  1105. # 检查登录状态
  1106. current_url = self.page.url
  1107. print(f"[{self.platform_name}] 当前 URL: {current_url}")
  1108. if "login" in current_url:
  1109. raise Exception("Cookie 已过期,请重新登录")
  1110. # 等待私信页面加载(使用多个选择器容错)
  1111. try:
  1112. await self.page.wait_for_selector('.private-msg-list-header', timeout=15000)
  1113. except:
  1114. # 尝试其他选择器
  1115. try:
  1116. await self.page.wait_for_selector('.weui-desktop-tab__navs__inner', timeout=10000)
  1117. print(f"[{self.platform_name}] 使用备用选择器加载成功")
  1118. except:
  1119. # 截图调试
  1120. screenshot_path = f"weixin_private_msg_{int(asyncio.get_event_loop().time())}.png"
  1121. await self.page.screenshot(path=screenshot_path)
  1122. print(f"[{self.platform_name}] 页面加载失败,截图: {screenshot_path}")
  1123. raise Exception(f"私信页面加载超时,当前 URL: {current_url}")
  1124. print(f"[{self.platform_name}] 私信页面加载完成")
  1125. # 处理两个 tab
  1126. total_replied = 0
  1127. for tab_name in ["打招呼消息", "私信"]:
  1128. replied_count = await self._process_tab_sessions(tab_name)
  1129. total_replied += replied_count
  1130. print(f"[{self.platform_name}] 自动回复完成,共回复 {total_replied} 条消息")
  1131. return {
  1132. 'success': True,
  1133. 'platform': self.platform_name,
  1134. 'replied_count': total_replied,
  1135. 'message': f'成功回复 {total_replied} 条私信'
  1136. }
  1137. except Exception as e:
  1138. import traceback
  1139. traceback.print_exc()
  1140. return {
  1141. 'success': False,
  1142. 'platform': self.platform_name,
  1143. 'error': str(e)
  1144. }
  1145. async def _process_tab_sessions(self, tab_name: str) -> int:
  1146. """处理指定 tab 下的所有会话"""
  1147. print(f"\n🔄 正在处理「{tab_name}」中的所有会话...")
  1148. if not self.page:
  1149. return 0
  1150. replied_count = 0
  1151. try:
  1152. # 点击 tab
  1153. if tab_name == "私信":
  1154. tab_link = self.page.locator('.weui-desktop-tab__navs__inner li').first.locator('a')
  1155. elif tab_name == "打招呼消息":
  1156. tab_link = self.page.locator('.weui-desktop-tab__navs__inner li').nth(1).locator('a')
  1157. else:
  1158. return 0
  1159. if await tab_link.is_visible():
  1160. await tab_link.click()
  1161. print(f" ➤ 已点击「{tab_name}」tab")
  1162. else:
  1163. print(f" ❌ 「{tab_name}」tab 不可见")
  1164. return 0
  1165. # 等待会话列表加载
  1166. try:
  1167. await self.page.wait_for_function("""
  1168. () => {
  1169. const hasSession = document.querySelectorAll('.session-wrap').length > 0;
  1170. const hasEmpty = !!document.querySelector('.empty-text');
  1171. return hasSession || hasEmpty;
  1172. }
  1173. """, timeout=8000)
  1174. print(" ✅ 会话列表区域已加载")
  1175. except:
  1176. print(" ⚠️ 等待会话列表超时,继续尝试读取...")
  1177. # 获取会话
  1178. session_wraps = self.page.locator('.session-wrap')
  1179. session_count = await session_wraps.count()
  1180. print(f" 💬 共找到 {session_count} 个会话")
  1181. if session_count == 0:
  1182. return 0
  1183. # 遍历每个会话
  1184. for idx in range(session_count):
  1185. try:
  1186. current_sessions = self.page.locator('.session-wrap')
  1187. if idx >= await current_sessions.count():
  1188. break
  1189. session = current_sessions.nth(idx)
  1190. user_name = await session.locator('.name').inner_text()
  1191. last_preview = await session.locator('.feed-info').inner_text()
  1192. print(f"\n ➤ [{idx+1}/{session_count}] 正在处理: {user_name} | 最后消息: {last_preview}")
  1193. await session.click()
  1194. await asyncio.sleep(2)
  1195. # 提取聊天历史
  1196. history = await self._extract_chat_history()
  1197. need_reply = (not history) or (not history[-1]["is_author"])
  1198. if need_reply:
  1199. reply_text = await self._generate_reply_with_ai(history)
  1200. if reply_text=="":
  1201. reply_text = self._generate_reply(history)
  1202. # # 生成回复
  1203. # if history and history[-1]["is_author"]:
  1204. # reply_text = await self._generate_reply_with_ai(history)
  1205. # else:
  1206. # reply_text = self._generate_reply(history)
  1207. if reply_text:
  1208. print(f" 📝 回复内容: {reply_text}")
  1209. try:
  1210. textarea = self.page.locator('.edit_area').first
  1211. send_btn = self.page.locator('button:has-text("发送")').first
  1212. if await textarea.is_visible() and await send_btn.is_visible():
  1213. await textarea.fill(reply_text)
  1214. await asyncio.sleep(0.5)
  1215. await send_btn.click()
  1216. print(" ✅ 已发送")
  1217. replied_count += 1
  1218. await asyncio.sleep(1.5)
  1219. else:
  1220. print(" ❌ 输入框或发送按钮不可见")
  1221. except Exception as e:
  1222. print(f" ❌ 发送失败: {e}")
  1223. else:
  1224. print(" ➤ 无需回复")
  1225. else:
  1226. print(" ➤ 最后一条是我发的,跳过回复")
  1227. except Exception as e:
  1228. print(f" ❌ 处理会话 {idx+1} 时出错: {e}")
  1229. continue
  1230. except Exception as e:
  1231. print(f"❌ 处理「{tab_name}」失败: {e}")
  1232. return replied_count
  1233. async def _extract_chat_history(self) -> list:
  1234. """精准提取聊天记录,区分作者(自己)和用户"""
  1235. if not self.page:
  1236. return []
  1237. history = []
  1238. message_wrappers = self.page.locator('.session-content-wrapper > div:not(.footer) > .text-wrapper')
  1239. count = await message_wrappers.count()
  1240. for i in range(count):
  1241. try:
  1242. wrapper = message_wrappers.nth(i)
  1243. # 判断方向
  1244. is_right = await wrapper.locator('.content-right').count() > 0
  1245. is_left = await wrapper.locator('.content-left').count() > 0
  1246. if not (is_left or is_right):
  1247. continue
  1248. # 提取消息文本
  1249. pre_el = wrapper.locator('pre.message-plain')
  1250. content = ''
  1251. if await pre_el.count() > 0:
  1252. content = await pre_el.inner_text()
  1253. content = content.strip()
  1254. if not content:
  1255. continue
  1256. # 获取头像
  1257. avatar_img = wrapper.locator('.avatar').first
  1258. avatar_src = ''
  1259. if await avatar_img.count() > 0:
  1260. avatar_src = await avatar_img.get_attribute("src") or ''
  1261. # 右侧 = 作者(自己)
  1262. is_author = is_right
  1263. # 获取用户名
  1264. if is_left:
  1265. name_el = wrapper.locator('.profile .name')
  1266. author_name = '用户'
  1267. if await name_el.count() > 0:
  1268. author_name = await name_el.inner_text()
  1269. else:
  1270. author_name = "我"
  1271. history.append({
  1272. "author": author_name,
  1273. "content": content,
  1274. "is_author": is_author,
  1275. "avatar": avatar_src
  1276. })
  1277. except Exception as e:
  1278. print(f" ⚠️ 解析第 {i+1} 条消息失败: {e}")
  1279. continue
  1280. return history
  1281. async def _generate_reply_with_ai(self, chat_history: list) -> str:
  1282. """使用 AI 生成智能回复"""
  1283. import requests
  1284. import json
  1285. try:
  1286. # 获取 AI 配置
  1287. ai_api_key = os.environ.get('DASHSCOPE_API_KEY', '')
  1288. ai_base_url = os.environ.get('DASHSCOPE_BASE_URL', 'https://dashscope.aliyuncs.com/compatible-mode/v1')
  1289. ai_model = os.environ.get('AI_MODEL', 'qwen-plus')
  1290. if not ai_api_key:
  1291. print("⚠️ 未配置 AI API Key,使用规则回复")
  1292. return self._generate_reply(chat_history)
  1293. # 构建对话上下文
  1294. messages = [{"role": "system", "content": "你是一个友好的微信视频号创作者助手,负责回复粉丝私信。请保持简洁、友好、专业的语气。回复长度不超过20字。"}]
  1295. for msg in chat_history:
  1296. role = "assistant" if msg["is_author"] else "user"
  1297. messages.append({
  1298. "role": role,
  1299. "content": msg["content"]
  1300. })
  1301. # 调用 AI API
  1302. headers = {
  1303. 'Authorization': f'Bearer {ai_api_key}',
  1304. 'Content-Type': 'application/json'
  1305. }
  1306. payload = {
  1307. "model": ai_model,
  1308. "messages": messages,
  1309. "max_tokens": 150,
  1310. "temperature": 0.8
  1311. }
  1312. print(" 🤖 正在调用 AI 生成回复...")
  1313. response = requests.post(
  1314. f"{ai_base_url}/chat/completions",
  1315. headers=headers,
  1316. json=payload,
  1317. timeout=30
  1318. )
  1319. if response.status_code != 200:
  1320. print(f" ⚠️ AI API 返回错误 {response.status_code},使用规则回复")
  1321. return self._generate_reply(chat_history)
  1322. result = response.json()
  1323. ai_reply = result.get('choices', [{}])[0].get('message', {}).get('content', '').strip()
  1324. if ai_reply:
  1325. print(f" ✅ AI 生成回复: {ai_reply}")
  1326. return ai_reply
  1327. else:
  1328. print(" ⚠️ AI 返回空内容,使用规则回复")
  1329. return self._generate_reply(chat_history)
  1330. except Exception as e:
  1331. print(f" ⚠️ AI 回复生成失败: {e},使用规则回复")
  1332. return self._generate_reply(chat_history)
  1333. def _generate_reply(self, chat_history: list) -> str:
  1334. """根据完整聊天历史生成回复(规则回复方式)"""
  1335. if not chat_history:
  1336. return "你好!感谢联系~"
  1337. # 检查最后一条是否是作者发的
  1338. if chat_history[-1]["is_author"]:
  1339. return "" # 不回复
  1340. # 找最后一条用户消息
  1341. last_user_msg = chat_history[-1]["content"]
  1342. # 简单规则回复
  1343. if "谢谢" in last_user_msg or "感谢" in last_user_msg:
  1344. return "不客气!欢迎常来交流~"
  1345. elif "你好" in last_user_msg or "在吗" in last_user_msg:
  1346. return "你好!请问有什么可以帮您的?"
  1347. elif "视频" in last_user_msg or "怎么拍" in last_user_msg:
  1348. return "视频是用手机拍摄的,注意光线和稳定哦!"
  1349. else:
  1350. return "收到!我会认真阅读您的留言~"