| 1 | # -*- coding: utf-8 -*- |
| 2 | from datetime import datetime |
| 3 | |
| 4 | import asyncio |
| 5 | import inspect |
| 6 | import os |
| 7 | import sys |
| 8 | from pathlib import Path |
| 9 | |
| 10 | from patchright.async_api import Page |
| 11 | from patchright.async_api import Playwright |
| 12 | from patchright.async_api import async_playwright |
| 13 | |
| 14 | from conf import BASE_DIR, DEBUG_MODE, LOCAL_CHROME_HEADLESS, LOCAL_CHROME_PATH |
| 15 | from uploader.base_video import BaseVideoUploader |
| 16 | from utils.base_social_media import set_init_script |
| 17 | from utils.login_qrcode import build_login_qrcode_path |
| 18 | from utils.login_qrcode import decode_qrcode_from_path |
| 19 | from utils.login_qrcode import print_terminal_qrcode |
| 20 | from utils.login_qrcode import remove_qrcode_file |
| 21 | from utils.login_qrcode import save_data_url_image |
| 22 | from utils.log import douyin_logger |
| 23 | |
| 24 | DOUYIN_PUBLISH_STRATEGY_IMMEDIATE = "immediate" |
| 25 | DOUYIN_PUBLISH_STRATEGY_SCHEDULED = "scheduled" |
| 26 | |
| 27 | |
| 28 | def _msg(emoji: str, text: str) -> str: |
| 29 | return f"{emoji} {text}" |
| 30 | |
| 31 | |
| 32 | async def _read_verify_code(code_file: str) -> str: |
| 33 | if os.path.exists(code_file): |
| 34 | with open(code_file, encoding="utf-8") as file_obj: |
| 35 | return file_obj.read().strip() |
| 36 | |
| 37 | if not sys.stdin or not sys.stdin.isatty(): |
| 38 | return "" |
| 39 | |
| 40 | try: |
| 41 | return (await asyncio.to_thread(input, "请输入抖音短信验证码(直接回车可稍后重试): ")).strip() |
| 42 | except (EOFError, OSError): |
| 43 | return "" |
| 44 | |
| 45 | |
| 46 | def _msg(emoji: str, text: str) -> str: |
| 47 | return f"{emoji} {text}" |
| 48 | |
| 49 | |
| 50 | async def _native_click(page, locator) -> bool: |
| 51 | """对元素做"真人级"点击:真实鼠标点中心 + 派发完整 pointer/mouse 事件序列。 |
| 52 | 抖音身份验证组件(uc_verification_component)只认这整套事件,不认单纯 click。 |
| 53 | 返回是否点击成功。""" |
| 54 | try: |
| 55 | await locator.scroll_into_view_if_needed(timeout=5000) |
| 56 | except Exception: |
| 57 | pass |
| 58 | try: |
| 59 | box = await locator.bounding_box() |
| 60 | except Exception: |
| 61 | box = None |
| 62 | if not box: |
| 63 | try: |
| 64 | await locator.click(timeout=8000) |
| 65 | return True |
| 66 | except Exception: |
| 67 | return False |
| 68 | x = box["x"] + box["width"] / 2 |
| 69 | y = box["y"] + box["height"] / 2 |
| 70 | try: |
| 71 | await page.mouse.move(x, y) |
| 72 | await asyncio.sleep(0.15) |
| 73 | await page.mouse.click(x, y) |
| 74 | await asyncio.sleep(0.2) |
| 75 | await page.evaluate( |
| 76 | """({x, y}) => { |
| 77 | const el = document.elementFromPoint(x, y); |
| 78 | if (!el) return; |
| 79 | const opts = {bubbles:true,cancelable:true,composed:true,clientX:x,clientY:y,view:window,pointerId:1,pointerType:'mouse',isPrimary:true,button:0,buttons:1}; |
| 80 | for (const t of ['pointerover','pointerenter','pointerdown','mousedown','pointerup','mouseup','click']) { |
| 81 | const C = t.startsWith('pointer') ? PointerEvent : MouseEvent; |
| 82 | try { el.dispatchEvent(new C(t, opts)); } catch(e){ try{ el.dispatchEvent(new MouseEvent(t,opts)); }catch(_){} } |
| 83 | } |
| 84 | }""", |
| 85 | {"x": x, "y": y}, |
| 86 | ) |
| 87 | return True |
| 88 | except Exception: |
| 89 | return False |
| 90 | |
| 91 | |
| 92 | async def _emit_qrcode_callback(qrcode_callback, payload: dict): |
| 93 | if not qrcode_callback: |
| 94 | return |
| 95 | |
| 96 | callback_result = qrcode_callback(payload) |
| 97 | if inspect.isawaitable(callback_result): |
| 98 | await callback_result |
| 99 | |
| 100 | |
| 101 | def _build_login_result(success: bool, status: str, message: str, account_file: str, qrcode: dict | None = None, current_url: str = "") -> dict: |
| 102 | return { |
| 103 | "success": success, |
| 104 | "status": status, |
| 105 | "message": message, |
| 106 | "account_file": str(account_file), |
| 107 | "qrcode": qrcode, |
| 108 | "current_url": current_url, |
| 109 | } |
| 110 | |
| 111 | |
| 112 | async def cookie_auth(account_file): |
| 113 | if not os.path.exists(account_file): |
| 114 | return False |
| 115 | |
| 116 | use_headless = os.environ.get("DOUYIN_COOKIE_AUTH_HEADLESS", "true").lower() in ("1", "true", "yes") |
| 117 | launch_kwargs = {"headless": use_headless, "channel": "chromium", "args": ["--no-sandbox", "--disable-blink-features=AutomationControlled"]} |
| 118 | for _attempt in range(3): |
| 119 | async with async_playwright() as playwright: |
| 120 | browser = await playwright.chromium.launch(**launch_kwargs) |
| 121 | try: |
| 122 | context = await browser.new_context(storage_state=account_file) |
| 123 | context = await set_init_script(context) |
| 124 | page = await context.new_page() |
| 125 | await page.goto("https://creator.douyin.com/creator-micro/content/upload", wait_until="domcontentloaded", timeout=90000) |
| 126 | await page.wait_for_timeout(2500) # 等页面稳定,避免瞬时跳转误判 |
| 127 | has_login = await page.get_by_text("手机号登录").count() or await page.get_by_text("扫码登录").count() |
| 128 | if "content/upload" in page.url and not has_login: |
| 129 | return True |
| 130 | except Exception: |
| 131 | pass |
| 132 | finally: |
| 133 | await browser.close() |
| 134 | return False |
| 135 | |
| 136 | |
| 137 | async def douyin_setup(account_file, handle=False, return_detail=False, qrcode_callback=None, headless: bool = LOCAL_CHROME_HEADLESS, cdp_url: str | None = None): |
| 138 | if not os.path.exists(account_file) or not await cookie_auth(account_file): |
| 139 | if not handle: |
| 140 | result = _build_login_result(False, "cookie_invalid", "cookie文件不存在或已失效", account_file) |
| 141 | return result if return_detail else False |
| 142 | douyin_logger.info(_msg("🥹", "cookie 失效了,准备打开浏览器重新登录")) |
| 143 | result = await douyin_cookie_gen(account_file, qrcode_callback=qrcode_callback, headless=headless, cdp_url=cdp_url) |
| 144 | return result if return_detail else result["success"] |
| 145 | |
| 146 | result = _build_login_result(True, "cookie_valid", "cookie有效", account_file) |
| 147 | return result if return_detail else True |
| 148 | |
| 149 | |
| 150 | async def _extract_douyin_qrcode_src(page: Page) -> str: |
| 151 | # 等 SPA 加载完成(不只等"扫码登录"文字,否则抖音慢加载时 30s 就超时)。 |
| 152 | # 给 domcontentloaded 后足够时间让客户端 JS 注入登录卡。 |
| 153 | try: |
| 154 | await page.wait_for_load_state("networkidle", timeout=15000) |
| 155 | except Exception: |
| 156 | pass |
| 157 | scan_login_tab = page.get_by_text("扫码登录", exact=True).first |
| 158 | # attached 状态:DOM 里出现即可,不要求 visible/渲染完整,避免 race |
| 159 | await scan_login_tab.wait_for(state="attached", timeout=60000) |
| 160 | |
| 161 | # 新版抖音创作者中心 (single_tab + animate_qrcode_container) 不再用 aria-label="二维码"。 |
| 162 | # 按优先级兜底多个 selector,至少一个能命中即可。 |
| 163 | qrcode_selectors = [ |
| 164 | 'div#animate_qrcode_container img[src^="data:image"]', |
| 165 | 'div[class*="animate_qrcode_container"] img[src^="data:image"]', |
| 166 | 'div[class*="scan_qrcode_login_content"] img[src^="data:image"]', |
| 167 | 'img[aria-label="二维码"]', |
| 168 | ] |
| 169 | last_err: Exception | None = None |
| 170 | for sel in qrcode_selectors: |
| 171 | qrcode_img = page.locator(sel).first |
| 172 | try: |
| 173 | await qrcode_img.wait_for(state="attached", timeout=10000) |
| 174 | except Exception as e: |
| 175 | last_err = e |
| 176 | continue |
| 177 | src = await qrcode_img.get_attribute("src") |
| 178 | if src: |
| 179 | return src |
| 180 | last_err = RuntimeError(f"selector {sel} 命中但 src 为空") |
| 181 | |
| 182 | raise RuntimeError(f"未获取到抖音登录二维码地址 (last_err={last_err})") |
| 183 | |
| 184 | |
| 185 | async def _save_douyin_qrcode(page: Page, account_file: str, previous_qrcode_path: Path | None = None, qrcode_callback=None) -> dict: |
| 186 | # 提取二维码 src 仅为了保存/终端显示;定位不到时不致命——有头浏览器里二维码可见,直接扫码即可 |
| 187 | try: |
| 188 | qrcode_src = await _extract_douyin_qrcode_src(page) |
| 189 | except Exception as exc: |
| 190 | douyin_logger.warning(_msg("😵", f"没定位到二维码元素({str(exc)[:50]})——请直接在弹出的浏览器里扫码,小人继续等登录跳转")) |
| 191 | return {"image_path": "", "image_data_url": ""} |
| 192 | qrcode_path = save_data_url_image(qrcode_src, build_login_qrcode_path(account_file)) |
| 193 | if previous_qrcode_path and previous_qrcode_path != qrcode_path: |
| 194 | if remove_qrcode_file(previous_qrcode_path): |
| 195 | douyin_logger.info(_msg("🧹", f"临时二维码文件已清理: {previous_qrcode_path}")) |
| 196 | douyin_logger.info(_msg("🖼️", f"二维码已经准备好啦,已保存到: {qrcode_path}")) |
| 197 | qrcode_content = decode_qrcode_from_path(qrcode_path) |
| 198 | if qrcode_content: |
| 199 | print_terminal_qrcode(qrcode_content, qrcode_path, "抖音APP") |
| 200 | else: |
| 201 | douyin_logger.warning(_msg("😵", f"终端没法完整显示二维码,请打开 {qrcode_path} 扫码")) |
| 202 | qrcode_info = { |
| 203 | "image_path": str(qrcode_path), |
| 204 | "image_data_url": qrcode_src, |
| 205 | } |
| 206 | await _emit_qrcode_callback(qrcode_callback, qrcode_info) |
| 207 | return qrcode_info |
| 208 | |
| 209 | |
| 210 | async def _is_douyin_login_completed(page: Page) -> bool: |
| 211 | # 登录后会跳到 creator-micro 下任意页(home/content 等);登录页是 creator.douyin.com/ 根路径 |
| 212 | if "creator.douyin.com/creator-micro" not in page.url: |
| 213 | return False |
| 214 | |
| 215 | login_markers = [ |
| 216 | page.get_by_text("扫码登录", exact=True).first, |
| 217 | page.get_by_text("手机号登录", exact=True).first, |
| 218 | page.get_by_text("二维码失效", exact=True).first, |
| 219 | page.get_by_role("img", name="二维码").first, |
| 220 | ] |
| 221 | |
| 222 | for marker in login_markers: |
| 223 | if not await marker.count(): |
| 224 | continue |
| 225 | try: |
| 226 | if await marker.is_visible(): |
| 227 | return False |
| 228 | except Exception: |
| 229 | continue |
| 230 | |
| 231 | return True |
| 232 | |
| 233 | |
| 234 | async def _wait_for_douyin_login(page: Page, account_file: str, qrcode_info: dict, qrcode_callback=None, poll_interval: int = 3, max_checks: int = 100) -> dict: |
| 235 | qrcode_path = Path(qrcode_info["image_path"]) if qrcode_info.get("image_path") else None |
| 236 | original_url = page.url |
| 237 | saw_2fa = False |
| 238 | for _ in range(max_checks): |
| 239 | if await _is_douyin_login_completed(page): |
| 240 | douyin_logger.info(_msg("🥳", f"扫码成功,已经跳转到登录后页面: {page.url}")) |
| 241 | return _build_login_result(True, "success", "抖音扫码登录成功", account_file, qrcode_info, page.url) |
| 242 | |
| 243 | # URL 变化 + sessionid 未到位 → 二验流程,继续等 |
| 244 | if page.url != original_url and not await _is_douyin_login_completed(page): |
| 245 | sms_input = page.locator('input[placeholder*="验证码"], input[type="tel"], input[placeholder*="短信"], input[placeholder*="手机号"]') |
| 246 | if await sms_input.count() > 0: |
| 247 | if not saw_2fa: |
| 248 | douyin_logger.warning(_msg("⚠️", f"检测到抖音短信/安全二次验证,请在弹出的浏览器中手动输入。等待 sessionid ({_}/{max_checks})")) |
| 249 | saw_2fa = True |
| 250 | await asyncio.sleep(poll_interval) |
| 251 | continue |
| 252 | |
| 253 | expired_box = page.get_by_text("二维码失效", exact=True).locator("..").first |
| 254 | if await expired_box.count() and await expired_box.is_visible(): |
| 255 | douyin_logger.warning(_msg("😵", "二维码失效了,小人马上去刷新")) |
| 256 | await expired_box.click() |
| 257 | await asyncio.sleep(1) |
| 258 | qrcode_info = await _save_douyin_qrcode(page, account_file, qrcode_path, qrcode_callback=qrcode_callback) |
| 259 | qrcode_path = Path(qrcode_info["image_path"]) if qrcode_info.get("image_path") else None |
| 260 | |
| 261 | await asyncio.sleep(poll_interval) |
| 262 | |
| 263 | return _build_login_result(False, "timeout", "等待抖音扫码登录超时", account_file, qrcode_info, page.url) |
| 264 | |
| 265 | async def douyin_cookie_gen( |
| 266 | account_file, |
| 267 | qrcode_callback=None, |
| 268 | poll_interval: int = 2, |
| 269 | max_checks: int = 60, |
| 270 | headless: bool = LOCAL_CHROME_HEADLESS, |
| 271 | cdp_url: str | None = None, |
| 272 | ): |
| 273 | async with async_playwright() as playwright: |
| 274 | if cdp_url: |
| 275 | browser = await playwright.chromium.connect_over_cdp(cdp_url) |
| 276 | context = browser.contexts[0] if browser.contexts else await browser.new_context() |
| 277 | should_close_context = False |
| 278 | else: |
| 279 | browser = await playwright.chromium.launch(headless=headless, channel="chromium") |
| 280 | context = await browser.new_context() |
| 281 | should_close_context = True |
| 282 | context = await set_init_script(context) |
| 283 | qrcode_path = None |
| 284 | result = _build_login_result(False, "failed", "抖音登录失败", account_file) |
| 285 | try: |
| 286 | page = await context.new_page() |
| 287 | await page.goto("https://creator.douyin.com/") |
| 288 | qrcode_info = await _save_douyin_qrcode(page, account_file, qrcode_callback=qrcode_callback) |
| 289 | qrcode_path = Path(qrcode_info["image_path"]) if qrcode_info.get("image_path") else None |
| 290 | douyin_logger.info(_msg("🧍", "请扫码,小人正在耐心等待登录完成")) |
| 291 | result = await _wait_for_douyin_login( |
| 292 | page, |
| 293 | account_file, |
| 294 | qrcode_info, |
| 295 | qrcode_callback=qrcode_callback, |
| 296 | poll_interval=poll_interval, |
| 297 | max_checks=max_checks, |
| 298 | ) |
| 299 | if result["success"]: |
| 300 | await asyncio.sleep(2) |
| 301 | await context.storage_state(path=account_file) |
| 302 | # 登录已通过"发布视频"确认成功、storage_state 刚从已登录浏览器抓下来, |
| 303 | # 不再用 flaky 的浏览器重检(那正是导致成功被误判为失败的老 bug)。 |
| 304 | # 只轻量确认文件里有 sessionid。 |
| 305 | try: |
| 306 | import json as _json |
| 307 | _d = _json.load(open(account_file)) |
| 308 | _has_sess = any(c.get("name") == "sessionid" and c.get("value") for c in _d.get("cookies", [])) |
| 309 | if not _has_sess: |
| 310 | result = _build_login_result( |
| 311 | False, |
| 312 | "cookie_invalid", |
| 313 | "抖音扫码流程结束,但 cookie 中无 sessionid", |
| 314 | account_file, |
| 315 | qrcode_info, |
| 316 | page.url, |
| 317 | ) |
| 318 | except Exception as _e: |
| 319 | douyin_logger.warning(_msg("⚠️", f"cookie 文件校验异常(忽略,按成功处理): {_e}")) |
| 320 | except Exception as exc: |
| 321 | result = _build_login_result(False, "failed", str(exc), account_file, current_url=page.url if "page" in locals() else "") |
| 322 | finally: |
| 323 | if remove_qrcode_file(qrcode_path): |
| 324 | douyin_logger.info(_msg("🧹", f"临时二维码文件已清理: {qrcode_path}")) |
| 325 | if not result["success"]: |
| 326 | douyin_logger.error(_msg("😢", f"登录失败: {result['message']}")) |
| 327 | if should_close_context: |
| 328 | await context.close() |
| 329 | await browser.close() |
| 330 | return result |
| 331 | |
| 332 | |
| 333 | class DouYinBaseUploader(BaseVideoUploader): |
| 334 | def __init__( |
| 335 | self, |
| 336 | publish_date: datetime | int, |
| 337 | account_file, |
| 338 | publish_strategy: str = DOUYIN_PUBLISH_STRATEGY_IMMEDIATE, |
| 339 | debug: bool = DEBUG_MODE, |
| 340 | headless: bool = LOCAL_CHROME_HEADLESS, |
| 341 | ): |
| 342 | self.publish_date = publish_date |
| 343 | self.account_file = account_file |
| 344 | self.publish_strategy = publish_strategy |
| 345 | self.debug = debug |
| 346 | self.date_format = "%Y年%m月%d日 %H:%M" |
| 347 | self.local_executable_path = LOCAL_CHROME_PATH |
| 348 | self.headless = headless |
| 349 | |
| 350 | async def validate_base_args(self): |
| 351 | if not os.path.exists(self.account_file): |
| 352 | raise RuntimeError(f"cookie文件不存在,请先完成抖音登录: {self.account_file}") |
| 353 | if not await cookie_auth(self.account_file): |
| 354 | raise RuntimeError(f"cookie文件已失效,请先完成抖音登录: {self.account_file}") |
| 355 | if self.publish_strategy not in {DOUYIN_PUBLISH_STRATEGY_IMMEDIATE, DOUYIN_PUBLISH_STRATEGY_SCHEDULED}: |
| 356 | raise ValueError(f"不支持的发布策略: {self.publish_strategy}") |
| 357 | |
| 358 | if self.publish_strategy == DOUYIN_PUBLISH_STRATEGY_SCHEDULED: |
| 359 | self.publish_date = self.validate_publish_date(self.publish_date) |
| 360 | else: |
| 361 | self.publish_date = 0 |
| 362 | |
| 363 | async def set_schedule_time_douyin(self, page, publish_date): |
| 364 | label_element = page.locator("[class^='radio']:has-text('定时发布')") |
| 365 | await label_element.click() |
| 366 | await asyncio.sleep(1) |
| 367 | publish_date_hour = publish_date.strftime("%Y-%m-%d %H:%M") |
| 368 | |
| 369 | await asyncio.sleep(1) |
| 370 | await page.locator('.semi-input[placeholder="日期和时间"]').click() |
| 371 | await page.keyboard.press("Control+KeyA") |
| 372 | await page.keyboard.type(str(publish_date_hour)) |
| 373 | await page.keyboard.press("Enter") |
| 374 | await asyncio.sleep(1) |
| 375 | |
| 376 | async def fill_title_and_description(self, page: Page, title: str, description: str, tags: list[str] | None = None): |
| 377 | # 2026-06 抖音发布页 DOM:标题=input[placeholder*=填写作品标题],描述=div.zone-container[contenteditable] |
| 378 | # version_2(post/video) 发布页要等视频上传完才渲染表单(实测约 40s),故等待超时给到 120s |
| 379 | title_input = page.locator('input[placeholder*="填写作品标题"]').first |
| 380 | await title_input.wait_for(state="visible", timeout=120000) |
| 381 | await title_input.fill(title[:30]) |
| 382 | |
| 383 | description_editor = page.locator('div.zone-container[contenteditable="true"]').first |
| 384 | await description_editor.wait_for(state="visible", timeout=120000) |
| 385 | await description_editor.click() |
| 386 | await page.keyboard.press("Control+KeyA") |
| 387 | await page.keyboard.press("Delete") |
| 388 | |
| 389 | # 先填正文描述,再填 #话题(此前 description 参数未被写入,导致抖音只有标签没有正文) |
| 390 | if description and description.strip(): |
| 391 | await page.keyboard.type(description.strip()) |
| 392 | |
| 393 | for tag in tags or []: |
| 394 | await page.keyboard.type(" #" + tag) |
| 395 | await page.keyboard.press("Space") |
| 396 | await page.keyboard.press("Escape") # 收起话题下拉,避免浮层拦截后续点击 |
| 397 | |
| 398 | async def set_location(self, page: Page, location: str = ""): |
| 399 | if not location: |
| 400 | return |
| 401 | await page.locator('div.semi-select span:has-text("输入地理位置")').click() |
| 402 | await page.keyboard.press("Backspace") |
| 403 | await page.wait_for_timeout(2000) |
| 404 | await page.keyboard.type(location) |
| 405 | await page.wait_for_selector('div[role="listbox"] [role="option"]', timeout=5000) |
| 406 | await page.locator('div[role="listbox"] [role="option"]').first.click() |
| 407 | |
| 408 | async def handle_product_dialog(self, page: Page, product_title: str): |
| 409 | await page.wait_for_timeout(2000) |
| 410 | await page.wait_for_selector('input[placeholder="请输入商品短标题"]', timeout=10000) |
| 411 | short_title_input = page.locator('input[placeholder="请输入商品短标题"]') |
| 412 | if not await short_title_input.count(): |
| 413 | douyin_logger.error(_msg("😵", "没找到商品短标题输入框")) |
| 414 | return False |
| 415 | |
| 416 | product_title = product_title[:10] |
| 417 | await short_title_input.fill(product_title) |
| 418 | await page.wait_for_timeout(1000) |
| 419 | |
| 420 | finish_button = page.locator('button:has-text("完成编辑")') |
| 421 | if "disabled" not in await finish_button.get_attribute("class"): |
| 422 | await finish_button.click() |
| 423 | douyin_logger.debug(_msg("🥳", "已点击“完成编辑”按钮")) |
| 424 | await page.wait_for_selector(".semi-modal-content", state="hidden", timeout=5000) |
| 425 | return True |
| 426 | |
| 427 | douyin_logger.error(_msg("😵", "“完成编辑”按钮是灰的,小人先把弹窗关掉")) |
| 428 | cancel_button = page.locator('button:has-text("取消")') |
| 429 | if await cancel_button.count(): |
| 430 | await cancel_button.click() |
| 431 | else: |
| 432 | close_button = page.locator(".semi-modal-close") |
| 433 | await close_button.click() |
| 434 | await page.wait_for_selector(".semi-modal-content", state="hidden", timeout=5000) |
| 435 | return False |
| 436 | |
| 437 | async def set_product_link(self, page: Page, product_link: str, product_title: str): |
| 438 | await page.wait_for_timeout(2000) |
| 439 | try: |
| 440 | await page.wait_for_selector("text=添加标签", timeout=10000) |
| 441 | dropdown = page.get_by_text("添加标签").locator("..").locator("..").locator("..").locator(".semi-select").first |
| 442 | if not await dropdown.count(): |
| 443 | douyin_logger.error(_msg("😵", "没找到标签下拉框")) |
| 444 | return False |
| 445 | douyin_logger.debug(_msg("🧍", "找到标签下拉框,小人准备选择“购物车”")) |
| 446 | await dropdown.click() |
| 447 | await page.wait_for_selector('[role="listbox"]', timeout=5000) |
| 448 | await page.locator('[role="option"]:has-text("购物车")').click() |
| 449 | douyin_logger.debug(_msg("🥳", "已经选中“购物车”")) |
| 450 | |
| 451 | await page.wait_for_selector('input[placeholder="粘贴商品链接"]', timeout=5000) |
| 452 | input_field = page.locator('input[placeholder="粘贴商品链接"]') |
| 453 | await input_field.fill(product_link) |
| 454 | douyin_logger.debug(_msg("🔗", f"商品链接已经填好了: {product_link}")) |
| 455 | |
| 456 | add_button = page.locator('span:has-text("添加链接")') |
| 457 | button_class = await add_button.get_attribute("class") |
| 458 | if "disable" in button_class: |
| 459 | douyin_logger.error(_msg("😵", "“添加链接”按钮现在点不了")) |
| 460 | return False |
| 461 | await add_button.click() |
| 462 | douyin_logger.debug(_msg("🥳", "已点击“添加链接”按钮")) |
| 463 | |
| 464 | await page.wait_for_timeout(2000) |
| 465 | error_modal = page.locator("text=未搜索到对应商品") |
| 466 | if await error_modal.count(): |
| 467 | confirm_button = page.locator('button:has-text("确定")') |
| 468 | await confirm_button.click() |
| 469 | douyin_logger.error(_msg("😢", "这个商品链接无效")) |
| 470 | return False |
| 471 | |
| 472 | if not await self.handle_product_dialog(page, product_title): |
| 473 | return False |
| 474 | |
| 475 | douyin_logger.debug(_msg("🥳", "商品链接设置好了")) |
| 476 | return True |
| 477 | except Exception as e: |
| 478 | douyin_logger.error(_msg("😢", f"设置商品链接时出错: {str(e)}")) |
| 479 | return False |
| 480 | |
| 481 | async def set_self_declaration(self, page: Page, declaration: str) -> bool: |
| 482 | """抖音「自主声明」:打开声明弹窗 → 单选声明类型 → 确定。 |
| 483 | |
| 484 | 真实弹窗(用户 F12 实测):header「请选择声明类型(单选)」,选项为 |
| 485 | label.semi-radio 内 span.semi-radio-addon 文本,「内容由AI生成」与 |
| 486 | 「内容为转载信息」「内容为个人观点或见解」等并列;底部 footer 的 |
| 487 | semi-button-primary =「确定」。 |
| 488 | |
| 489 | 入口/弹窗异步渲染;且填完话题后残留的 mention-wrapper/semi-portal 浮层会盖住入口, |
| 490 | 必须先清浮层再点。失败返回 False。 |
| 491 | |
| 492 | Args: |
| 493 | declaration: 声明类型文本(调用方显式传入) |
| 494 | """ |
| 495 | try: |
| 496 | # 清掉会遮挡入口的浮层(话题下拉/引导层),并让输入框失焦 |
| 497 | await self._clear_blocking_overlays(page) |
| 498 | |
| 499 | # 入口:点开声明弹窗(多个候选文案,native 仅作兜底) |
| 500 | entry = None |
| 501 | for etext in ["请选择自主声明", "请选择声明类型", "添加自主声明", "自主声明", "作品声明"]: |
| 502 | cand = page.get_by_text(etext).first |
| 503 | if await cand.count(): |
| 504 | entry = cand |
| 505 | break |
| 506 | if entry is not None: |
| 507 | try: |
| 508 | await entry.scroll_into_view_if_needed(timeout=3000) |
| 509 | except Exception: |
| 510 | pass |
| 511 | try: |
| 512 | await entry.click(timeout=6000) |
| 513 | except Exception: |
| 514 | await _native_click(page, entry) |
| 515 | await page.wait_for_timeout(1200) |
| 516 | |
| 517 | # 弹窗:header「请选择声明类型(单选)」 |
| 518 | dialog = page.locator(".semi-modal-content").filter(has_text="请选择声明类型").first |
| 519 | if await dialog.count() == 0: |
| 520 | dialog = page.locator(".semi-modal-body").filter(has_text="请选择声明类型").first |
| 521 | if await dialog.count() == 0: |
| 522 | douyin_logger.warning(_msg("🧾", "自主声明弹窗未打开,跳过声明继续发布")) |
| 523 | return False |
| 524 | await dialog.first.wait_for(state="visible", timeout=6000) |
| 525 | |
| 526 | # 选项:label.semi-radio 内 span.semi-radio-addon 精确匹配 |
| 527 | option = dialog.locator("label.semi-radio").filter( |
| 528 | has=page.locator(f'.semi-radio-addon:text-is("{declaration}")') |
| 529 | ).first |
| 530 | if await option.count() == 0: |
| 531 | option = dialog.locator("label.semi-radio").filter(has_text=declaration).first |
| 532 | if await option.count(): |
| 533 | try: |
| 534 | await option.click(timeout=6000) |
| 535 | except Exception: |
| 536 | await _native_click(page, option) |
| 537 | else: |
| 538 | await dialog.get_by_text(declaration, exact=True).first.click(timeout=6000, force=True) |
| 539 | await page.wait_for_timeout(400) |
| 540 | |
| 541 | # 确定:footer 的 primary 按钮 |
| 542 | confirm_btn = dialog.locator("button.semi-button-primary").filter(has_text="确定").first |
| 543 | if await confirm_btn.count() == 0: |
| 544 | confirm_btn = dialog.get_by_role("button", name="确定").first |
| 545 | if await confirm_btn.count() == 0: |
| 546 | confirm_btn = page.get_by_role("button", name="确定").first |
| 547 | try: |
| 548 | await confirm_btn.click(timeout=6000) |
| 549 | except Exception: |
| 550 | await _native_click(page, confirm_btn) |
| 551 | try: |
| 552 | await dialog.first.wait_for(state="hidden", timeout=6000) |
| 553 | except Exception: |
| 554 | pass |
| 555 | douyin_logger.success(_msg("🧾", f"自主声明已选择「{declaration}」")) |
| 556 | return True |
| 557 | except Exception as exc: |
| 558 | douyin_logger.warning(_msg("🧾", f"自主声明设置失败,跳过该步骤继续发布:{exc}")) |
| 559 | return False |
| 560 | |
| 561 | async def select_bgm(self, page: Page, bgm_name: str) -> bool: |
| 562 | """为图文发布选择 BGM:可选增强功能,搜索无结果或异常均跳过不中断发布。""" |
| 563 | try: |
| 564 | # 点击「选择音乐」按钮 |
| 565 | music_entry = page.locator('text="选择音乐"').nth(1) |
| 566 | if not await music_entry.count(): |
| 567 | music_entry = page.locator('text="选择音乐"').first |
| 568 | await music_entry.wait_for(state="visible", timeout=10000) |
| 569 | await music_entry.click() |
| 570 | |
| 571 | # 等待侧边栏出现并搜索 |
| 572 | sidesheet = page.locator(".semi-sidesheet-content").first |
| 573 | await sidesheet.wait_for(state="visible", timeout=8000) |
| 574 | search_input = sidesheet.locator('input.semi-input[placeholder="搜索音乐"]').first |
| 575 | await search_input.wait_for(state="visible", timeout=5000) |
| 576 | await search_input.fill(bgm_name) |
| 577 | await search_input.press("Enter") |
| 578 | |
| 579 | # 等待搜索结果 |
| 580 | await asyncio.sleep(2) |
| 581 | first_card = sidesheet.locator(".card-container-tmocjc").first |
| 582 | try: |
| 583 | await first_card.wait_for(state="visible", timeout=8000) |
| 584 | except Exception: |
| 585 | douyin_logger.warning(_msg("🎵", f"音乐「{bgm_name}」搜索结果为空,小人跳过")) |
| 586 | await self._close_music_sidesheet(page) |
| 587 | return False |
| 588 | |
| 589 | # 打印找到的音乐名称 |
| 590 | try: |
| 591 | song_name_el = first_card.locator(".song-name-oRge4d").first |
| 592 | if await song_name_el.count(): |
| 593 | song_name = await song_name_el.inner_text() |
| 594 | douyin_logger.info(_msg("🎵", f"小人找到了: {song_name}")) |
| 595 | except Exception: |
| 596 | pass |
| 597 | |
| 598 | # JS 点击「使用」(按钮 visibility:hidden,普通 click 无效) |
| 599 | apply_btn = first_card.locator(".apply-btn-LUPP0D").first |
| 600 | await apply_btn.evaluate("el => el.click()") |
| 601 | douyin_logger.info(_msg("🥳", f"BGM「{bgm_name}」已应用")) |
| 602 | |
| 603 | # 等待侧边栏关闭,超时则手动关闭 |
| 604 | try: |
| 605 | await sidesheet.wait_for(state="hidden", timeout=5000) |
| 606 | except Exception: |
| 607 | await self._close_music_sidesheet(page) |
| 608 | |
| 609 | return True |
| 610 | except Exception as exc: |
| 611 | douyin_logger.warning(_msg("🎵", f"添加 BGM 时出错,跳过该步骤继续发布:{exc}")) |
| 612 | try: |
| 613 | await self._close_music_sidesheet(page) |
| 614 | except Exception: |
| 615 | pass |
| 616 | return False |
| 617 | |
| 618 | async def _close_music_sidesheet(self, page: Page) -> None: |
| 619 | try: |
| 620 | close_btn = page.locator(".semi-sidesheet-close").first |
| 621 | if await close_btn.count() and await close_btn.is_visible(): |
| 622 | await close_btn.click() |
| 623 | await asyncio.sleep(1) |
| 624 | except Exception: |
| 625 | pass |
| 626 | |
| 627 | |
| 628 | class DouYinVideo(DouYinBaseUploader): |
| 629 | def __init__( |
| 630 | self, |
| 631 | title, |
| 632 | file_path, |
| 633 | tags, |
| 634 | publish_date: datetime | int, |
| 635 | account_file, |
| 636 | thumbnail_landscape_path=None, |
| 637 | productLink="", |
| 638 | productTitle="", |
| 639 | thumbnail_portrait_path=None, |
| 640 | desc: str | None = None, |
| 641 | collection_name: str | None = None, |
| 642 | publish_strategy: str = DOUYIN_PUBLISH_STRATEGY_IMMEDIATE, |
| 643 | debug: bool = DEBUG_MODE, |
| 644 | headless: bool = LOCAL_CHROME_HEADLESS, |
| 645 | declaration: str | None = None, |
| 646 | ): |
| 647 | super().__init__( |
| 648 | publish_date=publish_date, |
| 649 | account_file=account_file, |
| 650 | publish_strategy=publish_strategy, |
| 651 | debug=debug, |
| 652 | headless=headless, |
| 653 | ) |
| 654 | self.title = title |
| 655 | self.file_path = file_path |
| 656 | self.tags = tags |
| 657 | self.thumbnail_landscape_path = thumbnail_landscape_path |
| 658 | self.thumbnail_portrait_path = thumbnail_portrait_path |
| 659 | self.productLink = productLink |
| 660 | self.productTitle = productTitle |
| 661 | self.desc = desc or "" |
| 662 | self.collection_name = collection_name |
| 663 | self.declaration = declaration.strip() if declaration and declaration.strip() else None |
| 664 | |
| 665 | async def apply_self_declaration(self, page: Page) -> None: |
| 666 | if not self.declaration: |
| 667 | return |
| 668 | if not await self.set_self_declaration(page, self.declaration): |
| 669 | raise RuntimeError(f"自主声明「{self.declaration}」设置失败,拒绝继续发布") |
| 670 | |
| 671 | async def _clear_blocking_overlays(self, page: Page) -> None: |
| 672 | """清除会拦截点击的浮层:填完话题后残留的话题/@提及下拉(publish-mention-wrapper) |
| 673 | 及其所在 semi-portal、其它非模态 semi-portal(tooltip/popover)、shepherd 引导层, |
| 674 | 并让当前输入框失焦。合集/声明下拉自身的 portal 是"点开后"才创建,故此处清理不误伤。 |
| 675 | |
| 676 | 根因见 recorder.log 2026-08-10 05:31:apply_collection 点合集下拉时, |
| 677 | publish-mention-wrapper / semi-portal 拦截 pointer events → click 超时 → 归集被跳过。 |
| 678 | """ |
| 679 | try: |
| 680 | await page.keyboard.press("Escape") |
| 681 | except Exception: |
| 682 | pass |
| 683 | try: |
| 684 | await page.evaluate( |
| 685 | """() => { |
| 686 | if (document.activeElement && document.activeElement.blur) document.activeElement.blur(); |
| 687 | document.querySelectorAll('.shepherd-element,.shepherd-modal-overlay-container').forEach(e=>e.remove()); |
| 688 | document.querySelectorAll('[class*="mention-wrapper"]').forEach(e=>{ const p=e.closest('.semi-portal'); (p||e).remove(); }); |
| 689 | // 关闭残留的非模态 Semi 浮层 portal(保留模态框,如声明弹窗) |
| 690 | document.querySelectorAll('.semi-portal').forEach(e=>{ if(!e.querySelector('.semi-modal, .semi-modal-content')) e.remove(); }); |
| 691 | }""" |
| 692 | ) |
| 693 | except Exception: |
| 694 | pass |
| 695 | await page.wait_for_timeout(400) |
| 696 | |
| 697 | async def apply_collection(self, page: Page) -> None: |
| 698 | """在发布表单页"添加合集"区选择目标合集(Semi Design select,字节组件库)。 |
| 699 | |
| 700 | 结构与快手(Ant Design)不同:合集名是纯文本 span.option-title-*,无 label 属性, |
| 701 | 用文本精确匹配。触发器用专属 class .select-collection-* 定位(页面唯一,第一级 |
| 702 | "合集/系列"类型下拉与此无关,不会误选)。找不到匹配合集时按 Escape 收起下拉, |
| 703 | 保持未选状态直接发布(界面允许留空,不阻断主发布流程)。 |
| 704 | """ |
| 705 | if not self.collection_name: |
| 706 | return |
| 707 | try: |
| 708 | # 关键修复:填完话题后残留的话题/@提及下拉(publish-mention-wrapper)及 semi-portal |
| 709 | # 浮层盖在"添加合集"下拉上,普通 click 全点在遮罩上→超时→归集被跳过。先清浮层再点。 |
| 710 | await self._clear_blocking_overlays(page) |
| 711 | |
| 712 | trigger = page.locator('[class*="select-collection-"]').first |
| 713 | if await trigger.count() == 0: |
| 714 | douyin_logger.warning(_msg("😵", "未找到\"添加合集\"下拉框,跳过归集")) |
| 715 | return |
| 716 | selection = trigger.locator(".semi-select-selection") |
| 717 | try: |
| 718 | await selection.click(timeout=5000) |
| 719 | except Exception: |
| 720 | await self._clear_blocking_overlays(page) |
| 721 | await _native_click(page, selection) |
| 722 | await page.wait_for_timeout(800) |
| 723 | |
| 724 | option = page.locator(".semi-select-option.collection-option").filter( |
| 725 | has=page.locator(f'[class*="option-title-"]:text-is("{self.collection_name}")') |
| 726 | ) |
| 727 | if await option.count() == 0: |
| 728 | douyin_logger.warning( |
| 729 | _msg("😵", f"合集下拉框未找到「{self.collection_name}」,跳过归集,保持未选状态") |
| 730 | ) |
| 731 | await page.keyboard.press("Escape") |
| 732 | await page.wait_for_timeout(300) |
| 733 | return |
| 734 | |
| 735 | try: |
| 736 | await option.first.click(timeout=5000) |
| 737 | except Exception: |
| 738 | await _native_click(page, option.first) |
| 739 | await page.wait_for_timeout(500) |
| 740 | douyin_logger.success(_msg("🥳", f"已选择合集:{self.collection_name}")) |
| 741 | except Exception as exc: |
| 742 | douyin_logger.warning(_msg("😵", f"选择合集失败,跳过归集继续发布: {exc}")) |
| 743 | try: |
| 744 | await page.keyboard.press("Escape") |
| 745 | except Exception: |
| 746 | pass |
| 747 | |
| 748 | async def _submit_sms_verify_code(self, page: Page, sms_input, code: str, code_file: str) -> bool: |
| 749 | douyin_logger.info(_msg("✍️", f"已获取验证码,准备填入: {code}")) |
| 750 | await sms_input.click() |
| 751 | await sms_input.fill(code) |
| 752 | douyin_logger.info(_msg("✅", "验证码已填入输入框")) |
| 753 | await page.wait_for_timeout(500) |
| 754 | |
| 755 | verify_btn = page.locator('div.uc-ui-verify_sms-verify_button:has-text("验证")').first |
| 756 | if await verify_btn.count() and await verify_btn.is_visible(): |
| 757 | try: |
| 758 | await verify_btn.click(force=True) |
| 759 | douyin_logger.success(_msg("✅", "已点击「验证」按钮(force)")) |
| 760 | except Exception: |
| 761 | await page.eval_on_selector('div.uc-ui-verify_sms-verify_button', 'el => el.click()') |
| 762 | douyin_logger.success(_msg("✅", "已点击「验证」按钮(JS)")) |
| 763 | else: |
| 764 | verify_by_text = page.get_by_text("验证", exact=True).first |
| 765 | if await verify_by_text.count(): |
| 766 | await verify_by_text.click(force=True) |
| 767 | douyin_logger.success(_msg("✅", "已点击「验证」按钮(text)")) |
| 768 | else: |
| 769 | douyin_logger.warning(_msg("⚠️", "未找到验证按钮,尝试按Enter")) |
| 770 | await page.keyboard.press("Enter") |
| 771 | |
| 772 | if os.path.exists(code_file): |
| 773 | os.remove(code_file) |
| 774 | douyin_logger.info(_msg("🧹", "验证码文件已清理")) |
| 775 | |
| 776 | await page.wait_for_timeout(3000) |
| 777 | douyin_logger.info(_msg("🔄", "验证码处理完成,继续发布流程")) |
| 778 | return True |
| 779 | |
| 780 | async def validate_upload_args(self): |
| 781 | await self.validate_base_args() |
| 782 | if not self.title or not str(self.title).strip(): |
| 783 | raise ValueError("视频模式下,title 是必须的") |
| 784 | |
| 785 | self.file_path = str(self.validate_video_file(self.file_path)) |
| 786 | if self.thumbnail_landscape_path: |
| 787 | self.thumbnail_landscape_path = str(self.validate_image_file(self.thumbnail_landscape_path)) |
| 788 | if self.thumbnail_portrait_path: |
| 789 | self.thumbnail_portrait_path = str(self.validate_image_file(self.thumbnail_portrait_path)) |
| 790 | |
| 791 | async def handle_upload_error(self, page): |
| 792 | douyin_logger.warning(_msg("😵", "视频上传摔了一跤,小人马上重新上传")) |
| 793 | await page.locator('div.progress-div [class^="upload-btn-input"]').set_input_files(self.file_path) |
| 794 | |
| 795 | async def handle_auto_video_cover(self, page): |
| 796 | if await page.get_by_text("请设置封面后再发布").first.is_visible(): |
| 797 | douyin_logger.info(_msg("🧍", "发布前还得先把封面弄好")) |
| 798 | recommend_cover = page.locator('[class^="recommendCover-"]').first |
| 799 | if await recommend_cover.count(): |
| 800 | douyin_logger.info(_msg("🏃", "小人去选第一个推荐封面")) |
| 801 | try: |
| 802 | await recommend_cover.click() |
| 803 | await asyncio.sleep(1) |
| 804 | confirm_text = "是否确认应用此封面?" |
| 805 | if await page.get_by_text(confirm_text).first.is_visible(): |
| 806 | douyin_logger.info(_msg("🪟", f"弹出确认框了: {confirm_text}")) |
| 807 | await page.get_by_role("button", name="确定").click() |
| 808 | douyin_logger.info(_msg("🥳", "推荐封面已经应用")) |
| 809 | await asyncio.sleep(1) |
| 810 | douyin_logger.info(_msg("🥳", "封面选择流程完成")) |
| 811 | return True |
| 812 | except Exception as e: |
| 813 | douyin_logger.warning(_msg("😵", f"推荐封面没选成功: {e}")) |
| 814 | return False |
| 815 | |
| 816 | async def set_thumbnail(self, page: Page): |
| 817 | if not self.thumbnail_landscape_path and not self.thumbnail_portrait_path: |
| 818 | return |
| 819 | |
| 820 | douyin_logger.info(_msg("🏃", "小人正在设置视频封面")) |
| 821 | # 先清掉 shepherd 新手引导浮层,否则它会拦截封面点击导致弹窗打不开 |
| 822 | await page.evaluate( |
| 823 | "() => document.querySelectorAll('.shepherd-element,.shepherd-modal-overlay-container').forEach(e=>e.remove())" |
| 824 | ) |
| 825 | |
| 826 | cover_area = page.locator('[class*="cover-"]').filter(has=page.locator("img")).first |
| 827 | if not await cover_area.count(): |
| 828 | cover_area = page.locator('[class*="cover"]').first |
| 829 | |
| 830 | # 打开封面弹窗:抖音组件对普通/force click 常静默无效(和"完成"按钮同病), |
| 831 | # 统一用 _native_click 派发完整原生事件序列;点后校验弹窗是否出现,没出现就重试。 |
| 832 | cover_locator_str = 'div.dy-creator-content-modal' |
| 833 | cover_locator = page.locator(cover_locator_str).first |
| 834 | opened = False |
| 835 | # 刚上传完页面还在过渡,先等封面区渲染稳定,去掉"页面没稳就点空"这个诱因 |
| 836 | try: |
| 837 | await cover_area.wait_for(state="visible", timeout=8000) |
| 838 | except Exception: |
| 839 | pass |
| 840 | await page.wait_for_timeout(1500) |
| 841 | for attempt in range(5): |
| 842 | # hover 若干次,等「编辑封面/选择封面」入口真正浮现,避免回退到封面区中心点空 |
| 843 | trigger = None |
| 844 | trigger_txt = "封面区域" |
| 845 | for _ in range(3): |
| 846 | try: |
| 847 | await cover_area.hover(force=True) |
| 848 | await page.wait_for_timeout(600) |
| 849 | except Exception: |
| 850 | pass |
| 851 | for txt in ["编辑封面", "选择封面", "设置封面"]: |
| 852 | t = page.get_by_text(txt, exact=True).first |
| 853 | if await t.count() and await t.is_visible(): |
| 854 | trigger, trigger_txt = t, txt |
| 855 | break |
| 856 | if trigger is not None: |
| 857 | break |
| 858 | if trigger is None: |
| 859 | trigger = cover_area |
| 860 | # 每轮都用 _native_click(force click 对抖音自定义组件常静默失效,白耗时间) |
| 861 | await _native_click(page, trigger) |
| 862 | douyin_logger.info(_msg("🖼️", f"已点「{trigger_txt}」尝试打开封面弹窗(第{attempt + 1}次)")) |
| 863 | try: |
| 864 | await page.wait_for_selector(cover_locator_str, timeout=5000) |
| 865 | opened = True |
| 866 | break |
| 867 | except Exception: |
| 868 | continue |
| 869 | if not opened: |
| 870 | douyin_logger.warning(_msg("⚠️", "封面弹窗打不开,跳过自定义封面继续发布(交给推荐封面兜底)")) |
| 871 | return |
| 872 | |
| 873 | await page.wait_for_timeout(1500) |
| 874 | |
| 875 | # 封面弹窗内有两个 input.semi-upload-hidden-input(各自还带一个 -replace 兄弟): |
| 876 | # ① 左侧「生成参考图」(AI封面参考图)——drag 区是 semi-upload-drag-area-custom,只有个 + 图标; |
| 877 | # ② 帧选择区「上传封面」——drag 区含 .semi-upload-drag-area-main-text「点击上传文件或拖拽…」。 |
| 878 | # 旧代码用 .first 取到了①,封面被塞进 AI 参考图槽→真封面没设上、检测/AI生成一直转, |
| 879 | # 「完成」永远关不掉弹窗→挡住发布→超时(用户 F12 实测的真根因)。 |
| 880 | # 改为按 main-text 拖拽区精确定位②的上传 input,取不到再 .last 兜底。 |
| 881 | cover_upload = cover_locator.locator( |
| 882 | '.semi-upload:has(.semi-upload-drag-area-main-text) input.semi-upload-hidden-input' |
| 883 | ).first |
| 884 | if await cover_upload.count() == 0: |
| 885 | cover_upload = cover_locator.locator("input.semi-upload-hidden-input").last |
| 886 | |
| 887 | if self.thumbnail_portrait_path: |
| 888 | # 弹窗默认就在“设置竖封面”页;防御性点一下 tab(已激活则忽略) |
| 889 | try: |
| 890 | await cover_locator.get_by_text("设置竖封面", exact=True).first.click(timeout=3000) |
| 891 | await page.wait_for_timeout(800) |
| 892 | except Exception: |
| 893 | pass |
| 894 | await cover_upload.set_input_files(self.thumbnail_portrait_path) |
| 895 | await page.wait_for_timeout(3000) |
| 896 | douyin_logger.info(_msg("🖼️", "竖版封面已上传到预览")) |
| 897 | elif self.thumbnail_landscape_path: |
| 898 | try: |
| 899 | await cover_locator.get_by_text("设置横封面", exact=True).first.click(timeout=3000) |
| 900 | await page.wait_for_timeout(800) |
| 901 | except Exception: |
| 902 | pass |
| 903 | await cover_upload.set_input_files(self.thumbnail_landscape_path) |
| 904 | await page.wait_for_timeout(3000) |
| 905 | douyin_logger.info(_msg("🖼️", "横版封面已上传到预览")) |
| 906 | |
| 907 | # ── 等"完成"按钮解禁:封面图处理完成前,"完成"是 semi-button-disabled,点了无效 ── |
| 908 | def _finish_btn(): |
| 909 | return cover_locator.get_by_role("button", name="完成", exact=True).first |
| 910 | |
| 911 | for _ in range(30): # 最多 ~15s 等图片处理、按钮解禁 |
| 912 | try: |
| 913 | b = _finish_btn() |
| 914 | if await b.count(): |
| 915 | cls = await b.get_attribute("class") or "" |
| 916 | if "semi-button-disabled" not in cls: |
| 917 | break |
| 918 | except Exception: |
| 919 | pass |
| 920 | await page.wait_for_timeout(500) |
| 921 | |
| 922 | # ── 点"完成"并验证弹窗真正 detach ── |
| 923 | # 抖音自定义组件普通 click 可能不抛异常也不生效,所以每轮点后都校验弹窗是否消失: |
| 924 | # 消失才算成功;否则升级 _native_click、处理可能的二次确认、最后 Esc 兜底。 |
| 925 | closed = False |
| 926 | for attempt in range(4): |
| 927 | btn = _finish_btn() |
| 928 | if not await btn.count(): |
| 929 | btn = cover_locator.locator("button.semi-button").filter(has_text="完成").first |
| 930 | if await btn.count() and await btn.is_visible(): |
| 931 | try: |
| 932 | await btn.click(timeout=4000) |
| 933 | except Exception: |
| 934 | pass |
| 935 | await page.wait_for_timeout(1500) |
| 936 | if await cover_locator.count() == 0: |
| 937 | closed = True |
| 938 | break |
| 939 | # 普通点没关掉 → 派发完整原生事件序列 |
| 940 | await _native_click(page, btn) |
| 941 | await page.wait_for_timeout(1500) |
| 942 | if await cover_locator.count() == 0: |
| 943 | closed = True |
| 944 | break |
| 945 | |
| 946 | # 点"完成"后抖音可能弹二次确认(如未设横封面时问"确定完成?")→ 点确认类按钮 |
| 947 | for cname in ["确定", "确认", "仍然完成", "仍要完成", "继续"]: |
| 948 | confirm = page.locator(".semi-modal-content").get_by_role("button", name=cname, exact=True).first |
| 949 | if await confirm.count() and await confirm.is_visible(): |
| 950 | await _native_click(page, confirm) |
| 951 | await page.wait_for_timeout(1500) |
| 952 | break |
| 953 | if await cover_locator.count() == 0: |
| 954 | closed = True |
| 955 | break |
| 956 | |
| 957 | # 仍没关掉:Esc 兜底后再验证一次 |
| 958 | douyin_logger.debug(_msg("🖼️", f"封面「完成」后弹窗未关,重试(第{attempt + 1}次)")) |
| 959 | await page.keyboard.press("Escape") |
| 960 | await page.wait_for_timeout(1000) |
| 961 | if await cover_locator.count() == 0: |
| 962 | closed = True |
| 963 | break |
| 964 | |
| 965 | if closed: |
| 966 | douyin_logger.info(_msg("🥳", "视频封面设置完成,弹窗已关闭")) |
| 967 | else: |
| 968 | douyin_logger.warning(_msg("⚠️", "封面弹窗未能关闭,可能挡住自主声明/发布")) |
| 969 | |
| 970 | |
| 971 | async def upload(self, playwright: Playwright) -> None: |
| 972 | douyin_logger.info(_msg("🧍", "小人先检查 cookie、视频文件、封面和发布时间")) |
| 973 | await self.validate_upload_args() |
| 974 | douyin_logger.info(_msg("🥳", "上传前检查通过")) |
| 975 | |
| 976 | browser = await playwright.chromium.launch(headless=self.headless, channel="chromium", args=["--no-sandbox", "--disable-blink-features=AutomationControlled"]) |
| 977 | context = await browser.new_context( |
| 978 | storage_state=f"{self.account_file}", |
| 979 | permissions=["geolocation"], |
| 980 | ) |
| 981 | context = await set_init_script(context) |
| 982 | |
| 983 | page = await context.new_page() |
| 984 | await page.goto("https://creator.douyin.com/creator-micro/content/upload", wait_until="domcontentloaded", timeout=90000) |
| 985 | douyin_logger.info(_msg("🏃", f"小人开始搬运视频: {self.title}.mp4")) |
| 986 | douyin_logger.info(_msg("🧭", "小人正在赶往上传主页")) |
| 987 | await page.wait_for_url("https://creator.douyin.com/creator-micro/content/upload", timeout=90000) |
| 988 | |
| 989 | # ── 进入页面后可能弹身份验证(短信验证码)或被踢到登录页 ── |
| 990 | await page.wait_for_timeout(2000) |
| 991 | |
| 992 | # 确认已经在上传页(非登录页),再找上传 input |
| 993 | # 用更精确的选择器避免匹配到登录表单的 input |
| 994 | upload_input = page.locator("input.upload-btn-input, div[class^='container'] input[accept]").first |
| 995 | if not await upload_input.count(): |
| 996 | # 兜底:排除登录页的 input |
| 997 | upload_input = page.locator("div[class^='container'] input[type='file'], div[class^='container'] input.upload-input").first |
| 998 | if not await upload_input.count(): |
| 999 | # 最终兜底 |
| 1000 | upload_input = page.locator("div[class^='container'] input").first |
| 1001 | await upload_input.wait_for(state="attached", timeout=60000) |
| 1002 | await upload_input.set_input_files(self.file_path) |
| 1003 | |
| 1004 | while True: |
| 1005 | try: |
| 1006 | await page.wait_for_url( |
| 1007 | "https://creator.douyin.com/creator-micro/content/publish?enter_from=publish_page", |
| 1008 | timeout=3000, |
| 1009 | ) |
| 1010 | douyin_logger.info(_msg("🥳", "已经进入 version_1 发布页面")) |
| 1011 | break |
| 1012 | except Exception: |
| 1013 | try: |
| 1014 | await page.wait_for_url( |
| 1015 | "https://creator.douyin.com/creator-micro/content/post/video?enter_from=publish_page", |
| 1016 | timeout=3000, |
| 1017 | ) |
| 1018 | douyin_logger.info(_msg("🥳", "已经进入 version_2 发布页面")) |
| 1019 | break |
| 1020 | except Exception: |
| 1021 | douyin_logger.debug(_msg("🧍", "还没进到视频发布页面,小人继续等一会")) |
| 1022 | await asyncio.sleep(0.5) |
| 1023 | |
| 1024 | await asyncio.sleep(1) |
| 1025 | douyin_logger.info(_msg("✍️", "小人开始填标题、描述和话题")) |
| 1026 | await self.fill_title_and_description(page, self.title, self.desc, self.tags) |
| 1027 | douyin_logger.info(_msg("🏷️", f"小人一共贴了 {len(self.tags)} 个话题")) |
| 1028 | |
| 1029 | while True: |
| 1030 | try: |
| 1031 | number = await page.locator('[class^="long-card"] div:has-text("重新上传")').count() |
| 1032 | if number > 0: |
| 1033 | douyin_logger.success(_msg("🥳", "视频已经传完啦")) |
| 1034 | break |
| 1035 | douyin_logger.info(_msg("🏃", "小人正在努力上传视频")) |
| 1036 | await asyncio.sleep(2) |
| 1037 | if await page.locator('div.progress-div > div:has-text("上传失败")').count(): |
| 1038 | douyin_logger.error(_msg("😵", "检测到上传失败,小人准备重试")) |
| 1039 | await self.handle_upload_error(page) |
| 1040 | except Exception: |
| 1041 | douyin_logger.debug(_msg("🧍", "小人还在等视频上传完成")) |
| 1042 | await asyncio.sleep(2) |
| 1043 | |
| 1044 | if self.productLink and self.productTitle: |
| 1045 | douyin_logger.info(_msg("🛒", "小人正在设置商品链接")) |
| 1046 | await self.set_product_link(page, self.productLink, self.productTitle) |
| 1047 | douyin_logger.info(_msg("🥳", "商品链接设置完成")) |
| 1048 | |
| 1049 | # 自主声明:本项目成片含 AI 生成内容(TTS 配音 / AI 字幕 / AI 前贴片), |
| 1050 | # 按平台合规如实选「内容由AI生成」(与转载等并列,单选,无二级选项、无需填来源)。 |
| 1051 | if not self.declaration: |
| 1052 | self.declaration = "内容由AI生成" |
| 1053 | await self.apply_self_declaration(page) |
| 1054 | |
| 1055 | # 先归集:此时尚未打开封面弹窗,避免 dy-creator-content-portal 封面浮层拦截合集下拉 |
| 1056 | # (实测:封面弹窗在 headless 下常滞留"检测中"未关闭,会盖住"添加合集"下拉) |
| 1057 | await self.apply_collection(page) |
| 1058 | |
| 1059 | # 再设封面(放最后,关掉弹窗,避免残留浮层挡住发布按钮) |
| 1060 | await self.set_thumbnail(page) |
| 1061 | |
| 1062 | third_part_element = '[class^="info"] > [class^="first-part"] div div.semi-switch' |
| 1063 | if await page.locator(third_part_element).count(): |
| 1064 | if "semi-switch-checked" not in await page.eval_on_selector(third_part_element, "div => div.className"): |
| 1065 | await page.locator(third_part_element).locator("input.semi-switch-native-control").click() |
| 1066 | |
| 1067 | if self.publish_strategy == DOUYIN_PUBLISH_STRATEGY_SCHEDULED and self.publish_date != 0: |
| 1068 | await self.set_schedule_time_douyin(page, self.publish_date) |
| 1069 | |
| 1070 | sms_prompt_logged = False |
| 1071 | while True: |
| 1072 | try: |
| 1073 | # 移除会拦截发布按钮点击的新手引导/话题下拉浮层 |
| 1074 | await page.evaluate( |
| 1075 | "() => { document.querySelectorAll('.shepherd-element, .shepherd-modal-overlay-container, [class*=\"mention-wrapper\"]').forEach(e => e.remove()); }" |
| 1076 | ) |
| 1077 | # 检测并处理短信验证码弹窗 |
| 1078 | sms_input = page.locator('input[placeholder*="验证码"], input[type="tel"], input[placeholder*="短信"], input[placeholder*="手机号"]').first |
| 1079 | if await sms_input.count() and await sms_input.is_visible(): |
| 1080 | douyin_logger.warning(_msg("📱", "检测到短信验证码弹窗")) |
| 1081 | # 点击「获取验证码」按钮(仅首次) |
| 1082 | get_code_btn = page.get_by_text("获取验证码").first |
| 1083 | if await get_code_btn.count() and await get_code_btn.is_visible(): |
| 1084 | await get_code_btn.click() |
| 1085 | douyin_logger.info(_msg("📤", "已点击「获取验证码」,请查看手机短信")) |
| 1086 | code_file = os.path.join(BASE_DIR, "verify_code.txt") |
| 1087 | code = await _read_verify_code(code_file) |
| 1088 | if code: |
| 1089 | sms_prompt_logged = False |
| 1090 | await self._submit_sms_verify_code(page, sms_input, code, code_file) |
| 1091 | elif not sms_prompt_logged: |
| 1092 | douyin_logger.warning(_msg("⏳", f"等待验证码输入;可在交互终端直接输入,或写入文件: {code_file}")) |
| 1093 | sms_prompt_logged = True |
| 1094 | |
| 1095 | # ── 正常发布流程 ── |
| 1096 | publish_button = page.get_by_role("button", name="发布", exact=True) |
| 1097 | if await publish_button.count(): |
| 1098 | await publish_button.click(force=True) |
| 1099 | await page.wait_for_url( |
| 1100 | "https://creator.douyin.com/creator-micro/content/manage**", |
| 1101 | timeout=3000, |
| 1102 | ) |
| 1103 | douyin_logger.success(_msg("🥳", "视频发布成功,小人开心收工")) |
| 1104 | break |
| 1105 | except Exception: |
| 1106 | await self.handle_auto_video_cover(page) |
| 1107 | douyin_logger.info(_msg("🏃", "小人正在冲刺发布视频")) |
| 1108 | if self.debug: |
| 1109 | await page.screenshot(full_page=True) |
| 1110 | await asyncio.sleep(0.5) |
| 1111 | |
| 1112 | await context.storage_state(path=self.account_file) |
| 1113 | douyin_logger.success(_msg("🥳", "cookie 更新完毕")) |
| 1114 | await asyncio.sleep(2) |
| 1115 | await context.close() |
| 1116 | await browser.close() |
| 1117 | |
| 1118 | async def douyin_upload_video(self): |
| 1119 | async with async_playwright() as playwright: |
| 1120 | await self.upload(playwright) |
| 1121 | |
| 1122 | async def main(self): |
| 1123 | await self.douyin_upload_video() |
| 1124 | |
| 1125 | |
| 1126 | class DouYinNote(DouYinBaseUploader): |
| 1127 | def __init__( |
| 1128 | self, |
| 1129 | image_paths, |
| 1130 | note, |
| 1131 | tags, |
| 1132 | publish_date: datetime | int, |
| 1133 | account_file, |
| 1134 | title: str | None = None, |
| 1135 | publish_strategy: str = DOUYIN_PUBLISH_STRATEGY_IMMEDIATE, |
| 1136 | debug: bool = DEBUG_MODE, |
| 1137 | headless: bool = LOCAL_CHROME_HEADLESS, |
| 1138 | bgm: str = "", |
| 1139 | ): |
| 1140 | super().__init__( |
| 1141 | publish_date=publish_date, |
| 1142 | account_file=account_file, |
| 1143 | publish_strategy=publish_strategy, |
| 1144 | debug=debug, |
| 1145 | headless=headless, |
| 1146 | ) |
| 1147 | self.image_paths = image_paths |
| 1148 | self.note = note or "" |
| 1149 | self.title = title or (self.note[:30] if self.note else "") |
| 1150 | self.tags = tags or [] |
| 1151 | self.bgm = bgm or "" |
| 1152 | |
| 1153 | async def validate_upload_args(self): |
| 1154 | await self.validate_base_args() |
| 1155 | if not self.title or not str(self.title).strip(): |
| 1156 | raise ValueError("图文模式下,title 是必须的") |
| 1157 | |
| 1158 | if len(self.title) > 20: |
| 1159 | raise ValueError(f"标题不能超过20字符,当前: {len(self.title)}字符") |
| 1160 | |
| 1161 | if not self.image_paths: |
| 1162 | raise ValueError("图文模式下,图片是必须的") |
| 1163 | |
| 1164 | if isinstance(self.image_paths, (str, Path)): |
| 1165 | self.image_paths = [self.image_paths] |
| 1166 | |
| 1167 | if len(self.image_paths) > 35: |
| 1168 | raise ValueError("图文模式下最多只支持上传 35 张图片") |
| 1169 | |
| 1170 | note_len = len(self.note) if self.note else 0 |
| 1171 | if note_len > 1000: |
| 1172 | raise ValueError(f"正文不能超过1000字符,当前: {note_len}字符") |
| 1173 | |
| 1174 | normalized_image_paths = [] |
| 1175 | for image_path in self.image_paths: |
| 1176 | normalized_image_paths.append(str(self.validate_image_file(image_path))) |
| 1177 | self.image_paths = normalized_image_paths |
| 1178 | |
| 1179 | async def upload_note_content(self, page: Page) -> None: |
| 1180 | douyin_logger.info(_msg("🏃", f"小人开始搬运图文,共 {len(self.image_paths)} 张图片")) |
| 1181 | douyin_logger.info(_msg("🔀", "小人正在切换到图文发布")) |
| 1182 | await page.get_by_text("发布图文", exact=True).click() |
| 1183 | await page.wait_for_timeout(1000) |
| 1184 | |
| 1185 | douyin_logger.info(_msg("📤", "小人正在上传图片")) |
| 1186 | await page.locator("div[class^='container'] input[accept*='image']").set_input_files(self.image_paths) |
| 1187 | |
| 1188 | while True: |
| 1189 | try: |
| 1190 | await page.wait_for_url( |
| 1191 | "**/creator-micro/content/post/image?**", |
| 1192 | timeout=3000, |
| 1193 | ) |
| 1194 | douyin_logger.info(_msg("🥳", "已经进入图文发布页面")) |
| 1195 | break |
| 1196 | except Exception: |
| 1197 | douyin_logger.debug(_msg("🧍", "小人还在等图片上传完成")) |
| 1198 | await asyncio.sleep(0.5) |
| 1199 | |
| 1200 | await asyncio.sleep(1) |
| 1201 | douyin_logger.info(_msg("✍️", "小人开始填标题、描述和话题")) |
| 1202 | await self.fill_title_and_description(page, self.title, self.note, self.tags) |
| 1203 | title_len = len(self.title) if self.title else 0 |
| 1204 | tags_text = " ".join(f"#{t}" for t in self.tags) if self.tags else "" |
| 1205 | desc_and_tags_len = len(self.note or "") + (len(tags_text) + 2 if self.tags else 0) |
| 1206 | douyin_logger.info(_msg("📝", f"标题总字数: {title_len},描述+话题总字数: {desc_and_tags_len}")) |
| 1207 | douyin_logger.info(_msg("🏷️", f"小人一共贴了 {len(self.tags)} 个话题")) |
| 1208 | |
| 1209 | if self.bgm: |
| 1210 | await self.select_bgm(page, self.bgm) |
| 1211 | |
| 1212 | if self.publish_strategy == DOUYIN_PUBLISH_STRATEGY_SCHEDULED and self.publish_date != 0: |
| 1213 | await self.set_schedule_time_douyin(page, self.publish_date) |
| 1214 | |
| 1215 | while True: |
| 1216 | try: |
| 1217 | publish_button = page.get_by_role("button", name="发布", exact=True) |
| 1218 | if await publish_button.count(): |
| 1219 | await publish_button.click() |
| 1220 | await page.wait_for_url( |
| 1221 | "**/creator-micro/content/manage?enter_from=publish**", |
| 1222 | timeout=3000, |
| 1223 | ) |
| 1224 | douyin_logger.success(_msg("🥳", "图文发布成功,小人开心收工")) |
| 1225 | break |
| 1226 | except Exception: |
| 1227 | douyin_logger.info(_msg("🏃", "小人正在冲刺发布图文")) |
| 1228 | await asyncio.sleep(0.5) |
| 1229 | |
| 1230 | async def upload(self, playwright: Playwright) -> None: |
| 1231 | douyin_logger.info(_msg("🧍", "小人先检查 cookie、图片和发布时间")) |
| 1232 | await self.validate_upload_args() |
| 1233 | douyin_logger.info(_msg("🥳", "图文上传前检查通过")) |
| 1234 | |
| 1235 | browser = await playwright.chromium.launch(headless=self.headless, channel="chromium", args=["--no-sandbox", "--disable-blink-features=AutomationControlled"]) |
| 1236 | context = await browser.new_context( |
| 1237 | storage_state=f"{self.account_file}", |
| 1238 | permissions=["geolocation"], |
| 1239 | ) |
| 1240 | context = await set_init_script(context) |
| 1241 | |
| 1242 | upload_success = False |
| 1243 | try: |
| 1244 | page = await context.new_page() |
| 1245 | await page.goto("https://creator.douyin.com/creator-micro/content/upload", wait_until="domcontentloaded", timeout=90000) |
| 1246 | douyin_logger.info(_msg("🧭", "小人正在赶往图文发布页")) |
| 1247 | await page.wait_for_url("https://creator.douyin.com/creator-micro/content/upload", timeout=90000) |
| 1248 | |
| 1249 | await self.upload_note_content(page) |
| 1250 | upload_success = True |
| 1251 | finally: |
| 1252 | if upload_success: |
| 1253 | await context.storage_state(path=self.account_file) |
| 1254 | douyin_logger.success(_msg("🥳", "cookie 更新完毕")) |
| 1255 | await asyncio.sleep(2) |
| 1256 | await context.close() |
| 1257 | await browser.close() |
| 1258 | |
| 1259 | async def douyin_upload_note(self): |
| 1260 | async with async_playwright() as playwright: |
| 1261 | await self.upload(playwright) |
| 1262 |