douyin.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. # -*- coding: utf-8 -*-
  2. """
  3. 抖音视频发布器
  4. 参考: matrix/douyin_uploader/main.py
  5. """
  6. import asyncio
  7. import os
  8. from datetime import datetime
  9. from .base import BasePublisher, PublishParams, PublishResult
  10. class DouyinPublisher(BasePublisher):
  11. """
  12. 抖音视频发布器
  13. 使用 Playwright 自动化操作抖音创作者中心
  14. """
  15. platform_name = "douyin"
  16. login_url = "https://creator.douyin.com/"
  17. publish_url = "https://creator.douyin.com/creator-micro/content/upload"
  18. cookie_domain = ".douyin.com"
  19. async def set_schedule_time(self, publish_date: datetime):
  20. """设置定时发布"""
  21. if not self.page:
  22. return
  23. # 选择定时发布
  24. label_element = self.page.locator("label.radio-d4zkru:has-text('定时发布')")
  25. await label_element.click()
  26. await asyncio.sleep(1)
  27. # 输入时间
  28. publish_date_str = publish_date.strftime("%Y-%m-%d %H:%M")
  29. await self.page.locator('.semi-input[placeholder="日期和时间"]').click()
  30. await self.page.keyboard.press("Control+KeyA")
  31. await self.page.keyboard.type(str(publish_date_str))
  32. await self.page.keyboard.press("Enter")
  33. await asyncio.sleep(1)
  34. async def handle_upload_error(self, video_path: str):
  35. """处理上传错误,重新上传"""
  36. if not self.page:
  37. return
  38. print(f"[{self.platform_name}] 视频出错了,重新上传中...")
  39. await self.page.locator('div.progress-div [class^="upload-btn-input"]').set_input_files(video_path)
  40. async def publish(self, cookies: str, params: PublishParams) -> PublishResult:
  41. """发布视频到抖音"""
  42. print(f"\n{'='*60}")
  43. print(f"[{self.platform_name}] 开始发布视频")
  44. print(f"[{self.platform_name}] 视频路径: {params.video_path}")
  45. print(f"[{self.platform_name}] 标题: {params.title}")
  46. print(f"[{self.platform_name}] Headless: {self.headless}")
  47. print(f"{'='*60}")
  48. self.report_progress(5, "正在初始化浏览器...")
  49. # 初始化浏览器
  50. await self.init_browser()
  51. print(f"[{self.platform_name}] 浏览器初始化完成")
  52. # 解析并设置 cookies
  53. cookie_list = self.parse_cookies(cookies)
  54. print(f"[{self.platform_name}] 解析到 {len(cookie_list)} 个 cookies")
  55. await self.set_cookies(cookie_list)
  56. if not self.page:
  57. raise Exception("Page not initialized")
  58. # 检查视频文件
  59. if not os.path.exists(params.video_path):
  60. raise Exception(f"视频文件不存在: {params.video_path}")
  61. print(f"[{self.platform_name}] 视频文件存在,大小: {os.path.getsize(params.video_path)} bytes")
  62. self.report_progress(10, "正在打开上传页面...")
  63. # 访问上传页面
  64. await self.page.goto(self.publish_url)
  65. await self.page.wait_for_url(self.publish_url, timeout=30000)
  66. self.report_progress(15, "正在选择视频文件...")
  67. # 点击上传区域
  68. upload_div = self.page.locator("div[class*='container-drag']").first
  69. async with self.page.expect_file_chooser() as fc_info:
  70. await upload_div.click()
  71. file_chooser = await fc_info.value
  72. await file_chooser.set_files(params.video_path)
  73. # 等待跳转到发布页面
  74. self.report_progress(20, "等待进入发布页面...")
  75. for _ in range(60):
  76. try:
  77. await self.page.wait_for_url(
  78. "https://creator.douyin.com/creator-micro/content/post/video*",
  79. timeout=2000
  80. )
  81. break
  82. except:
  83. await asyncio.sleep(1)
  84. await asyncio.sleep(2)
  85. self.report_progress(30, "正在填充标题和话题...")
  86. # 填写标题
  87. title_input = self.page.get_by_text('作品标题').locator("..").locator(
  88. "xpath=following-sibling::div[1]").locator("input")
  89. if await title_input.count():
  90. await title_input.fill(params.title[:30])
  91. else:
  92. # 备用方式
  93. title_container = self.page.locator(".notranslate")
  94. await title_container.click()
  95. await self.page.keyboard.press("Control+KeyA")
  96. await self.page.keyboard.press("Delete")
  97. await self.page.keyboard.type(params.title)
  98. await self.page.keyboard.press("Enter")
  99. # 添加话题标签
  100. if params.tags:
  101. css_selector = ".zone-container"
  102. for tag in params.tags:
  103. print(f"[{self.platform_name}] 添加话题: #{tag}")
  104. await self.page.type(css_selector, "#" + tag)
  105. await self.page.press(css_selector, "Space")
  106. self.report_progress(40, "等待视频上传完成...")
  107. # 等待视频上传完成
  108. for _ in range(120):
  109. try:
  110. count = await self.page.locator("div").filter(has_text="重新上传").count()
  111. if count > 0:
  112. print(f"[{self.platform_name}] 视频上传完毕")
  113. break
  114. # 检查上传错误
  115. if await self.page.locator('div.progress-div > div:has-text("上传失败")').count():
  116. await self.handle_upload_error(params.video_path)
  117. await asyncio.sleep(3)
  118. except:
  119. await asyncio.sleep(3)
  120. self.report_progress(60, "处理视频设置...")
  121. # 关闭弹窗
  122. known_btn = self.page.get_by_role("button", name="我知道了")
  123. if await known_btn.count() > 0:
  124. await known_btn.first.click()
  125. await asyncio.sleep(2)
  126. # 设置位置
  127. try:
  128. await self.page.locator('div.semi-select span:has-text("输入地理位置")').click()
  129. await asyncio.sleep(1)
  130. await self.page.keyboard.press("Control+KeyA")
  131. await self.page.keyboard.press("Delete")
  132. await self.page.keyboard.type(params.location)
  133. await asyncio.sleep(1)
  134. await self.page.locator('div[role="listbox"] [role="option"]').first.click()
  135. except Exception as e:
  136. print(f"[{self.platform_name}] 设置位置失败: {e}")
  137. # 开启头条/西瓜同步
  138. try:
  139. third_part_element = '[class^="info"] > [class^="first-part"] div div.semi-switch'
  140. if await self.page.locator(third_part_element).count():
  141. class_name = await self.page.eval_on_selector(
  142. third_part_element, 'div => div.className')
  143. if 'semi-switch-checked' not in class_name:
  144. await self.page.locator(third_part_element).locator(
  145. 'input.semi-switch-native-control').click()
  146. except:
  147. pass
  148. # 定时发布
  149. if params.publish_date:
  150. self.report_progress(70, "设置定时发布...")
  151. await self.set_schedule_time(params.publish_date)
  152. self.report_progress(80, "正在发布...")
  153. print(f"[{self.platform_name}] 查找发布按钮...")
  154. # 点击发布
  155. publish_clicked = False
  156. for i in range(30):
  157. try:
  158. publish_btn = self.page.get_by_role('button', name="发布", exact=True)
  159. btn_count = await publish_btn.count()
  160. print(f"[{self.platform_name}] 发布按钮数量: {btn_count}")
  161. if btn_count > 0:
  162. print(f"[{self.platform_name}] 点击发布按钮...")
  163. await publish_btn.click()
  164. publish_clicked = True
  165. await self.page.wait_for_url(
  166. "https://creator.douyin.com/creator-micro/content/manage",
  167. timeout=5000
  168. )
  169. self.report_progress(100, "发布成功")
  170. print(f"[{self.platform_name}] 发布成功! 已跳转到内容管理页面")
  171. return PublishResult(
  172. success=True,
  173. platform=self.platform_name,
  174. message="发布成功"
  175. )
  176. except Exception as e:
  177. current_url = self.page.url
  178. print(f"[{self.platform_name}] 尝试 {i+1}/30, 当前URL: {current_url}")
  179. if "content/manage" in current_url:
  180. self.report_progress(100, "发布成功")
  181. print(f"[{self.platform_name}] 发布成功! 已在内容管理页面")
  182. return PublishResult(
  183. success=True,
  184. platform=self.platform_name,
  185. message="发布成功"
  186. )
  187. # 检查是否有错误提示
  188. try:
  189. error_toast = self.page.locator('[class*="toast"][class*="error"], [class*="error-tip"]')
  190. if await error_toast.count() > 0:
  191. error_text = await error_toast.first.text_content()
  192. if error_text:
  193. print(f"[{self.platform_name}] 检测到错误提示: {error_text}")
  194. raise Exception(f"发布失败: {error_text}")
  195. except:
  196. pass
  197. await asyncio.sleep(1)
  198. # 发布超时,保存截图
  199. screenshot_path = f"debug_publish_timeout_{self.platform_name}.png"
  200. await self.page.screenshot(path=screenshot_path, full_page=True)
  201. print(f"[{self.platform_name}] 发布超时,截图保存到: {screenshot_path}")
  202. raise Exception(f"发布超时(截图: {screenshot_path})")