返回 Social Auto Upload
main.py
1 # -*- coding: utf-8 -*-
2 from __future__ import annotations
3
4 import asyncio
5 import inspect
6 import os
7 from datetime import datetime
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 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.files_times import get_absolute_path
18 from utils.login_qrcode import build_login_qrcode_path
19 from utils.login_qrcode import decode_qrcode_from_path
20 from utils.login_qrcode import print_terminal_qrcode
21 from utils.login_qrcode import remove_qrcode_file
22 from utils.login_qrcode import save_data_url_image
23 from utils.log import kuaishou_logger
24
25 KUAISHOU_UPLOAD_URL = "https://cp.kuaishou.com/article/publish/video"
26 KUAISHOU_MANAGE_URL = "https://cp.kuaishou.com/article/manage/video?status=2&from=publish"
27 KUAISHOU_LOGIN_URL = "https://passport.kuaishou.com/pc/account/login/?sid=kuaishou.web.cp.api&callback=https%3A%2F%2Fcp.kuaishou.com%2Frest%2Finfra%2Fsts%3FfollowUrl%3Dhttps%253A%252F%252Fcp.kuaishou.com%252Farticle%252Fpublish%252Fvideo%26setRootDomain%3Dtrue"
28 KUAISHOU_UPLOAD_URL_PATTERN = "**/article/publish/video**"
29 KUAISHOU_MANAGE_URL_PATTERN = "**/article/manage/video?status=2&from=publish**"
30 KUAISHOU_COOKIE_INVALID_SELECTOR = "div.names div.container div.name:text('机构服务')"
31 KUAISHOU_PUBLISH_STRATEGY_IMMEDIATE = "immediate"
32 KUAISHOU_PUBLISH_STRATEGY_SCHEDULED = "scheduled"
33
34
35 def _msg(emoji: str, text: str) -> str:
36 return f"{emoji} {text}"
37
38
39 def _print_ks_qrcode(qrcode_content: str, qrcode_path: Path) -> None:
40 try:
41 print_terminal_qrcode(qrcode_content, qrcode_path, "快手APP", compact=False, border=2)
42 except TypeError as exc:
43 if "unexpected keyword argument 'compact'" not in str(exc):
44 raise
45 kuaishou_logger.warning(_msg("😵", "检测到旧版二维码打印函数,小人切回兼容模式继续登录"))
46 print_terminal_qrcode(qrcode_content, qrcode_path, "快手APP")
47
48
49 async def _emit_qrcode_callback(qrcode_callback, payload: dict):
50 if not qrcode_callback:
51 return
52
53 callback_result = qrcode_callback(payload)
54 if inspect.isawaitable(callback_result):
55 await callback_result
56
57
58 def _build_login_result(
59 success: bool,
60 status: str,
61 message: str,
62 account_file: str,
63 qrcode: dict | None = None,
64 current_url: str = "",
65 ) -> dict:
66 return {
67 "success": success,
68 "status": status,
69 "message": message,
70 "account_file": str(account_file),
71 "qrcode": qrcode,
72 "current_url": current_url,
73 }
74
75
76 async def _is_ks_cookie_invalid(page: Page, timeout: int = 5000) -> bool:
77 try:
78 await page.wait_for_selector(KUAISHOU_COOKIE_INVALID_SELECTOR, timeout=timeout)
79 return True
80 except Exception:
81 return False
82
83
84 async def _extract_ks_qrcode_src(page: Page) -> str:
85 login_form = page.locator("main#login-form").first
86 await login_form.wait_for(state="visible", timeout=30000)
87
88 qrcode_img = login_form.locator('div.qr-login img[alt="qrcode"]').first
89 try:
90 if not await qrcode_img.count() or not await qrcode_img.is_visible():
91 platform_switch = login_form.locator("div.platform-switch").first
92 await platform_switch.wait_for(state="visible", timeout=10000)
93 await platform_switch.click()
94 await asyncio.sleep(1)
95 except Exception:
96 platform_switch = login_form.locator("div.platform-switch").first
97 await platform_switch.wait_for(state="visible", timeout=10000)
98 await platform_switch.click()
99 await asyncio.sleep(1)
100
101 await qrcode_img.wait_for(state="visible", timeout=15000)
102
103 qrcode_src = await qrcode_img.get_attribute("src")
104 if not qrcode_src:
105 raise RuntimeError("未获取到快手登录二维码地址")
106
107 return qrcode_src
108
109
110 async def _save_ks_qrcode(page: Page, account_file: str, previous_qrcode_path: Path | None = None, qrcode_callback=None) -> dict:
111 qrcode_src = await _extract_ks_qrcode_src(page)
112 qrcode_path = save_data_url_image(qrcode_src, build_login_qrcode_path(account_file, suffix="ks_login_qrcode"))
113
114 if previous_qrcode_path and previous_qrcode_path != qrcode_path:
115 if remove_qrcode_file(previous_qrcode_path):
116 kuaishou_logger.info(_msg("🧹", f"临时二维码文件已清理: {previous_qrcode_path}"))
117
118 kuaishou_logger.info(_msg("🖼️", f"二维码已经准备好啦,已保存到: {qrcode_path}"))
119 qrcode_content = decode_qrcode_from_path(qrcode_path)
120 if qrcode_content:
121 _print_ks_qrcode(qrcode_content, qrcode_path)
122 else:
123 kuaishou_logger.warning(_msg("😵", f"终端没法完整显示二维码,请打开 {qrcode_path} 扫码"))
124
125 qrcode_info = {
126 "image_path": str(qrcode_path),
127 "image_data_url": qrcode_src,
128 }
129 await _emit_qrcode_callback(qrcode_callback, qrcode_info)
130 return qrcode_info
131
132
133 async def _is_ks_qrcode_expired(page: Page) -> bool:
134 expired_box = page.locator("div.qrcode-status.qrcode-status-timeout").first
135 try:
136 if not await expired_box.count():
137 return False
138 return await expired_box.is_visible()
139 except Exception:
140 return False
141
142
143 async def _is_ks_login_page_gone(page: Page) -> bool:
144 try:
145 login_form = page.locator("main#login-form").first
146 if not await login_form.count():
147 return True
148 return not await login_form.is_visible()
149 except Exception:
150 return True
151
152
153 async def cookie_auth(account_file):
154 async with async_playwright() as playwright:
155 if LOCAL_CHROME_PATH:
156 browser = await playwright.chromium.launch(headless=True, executable_path=LOCAL_CHROME_PATH)
157 else:
158 browser = await playwright.chromium.launch(headless=True, channel="chromium")
159 try:
160 context = await browser.new_context(storage_state=account_file)
161 context = await set_init_script(context)
162 page = await context.new_page()
163 await page.goto(KUAISHOU_UPLOAD_URL)
164 if await _is_ks_cookie_invalid(page):
165 kuaishou_logger.info(_msg("🥹", "cookie 已失效,得重新登录一下"))
166 return False
167
168 kuaishou_logger.success(_msg("🥳", "cookie 有效"))
169 return True
170 except Exception as exc:
171 kuaishou_logger.warning(_msg("😵", f"cookie 校验时出错,按失效处理: {exc}"))
172 return False
173 finally:
174 await browser.close()
175
176
177 async def ks_setup(account_file, handle=False, return_detail=False, qrcode_callback=None, headless: bool = LOCAL_CHROME_HEADLESS, cdp_url: str | None = None):
178 account_file = get_absolute_path(account_file, "ks_uploader")
179 if not os.path.exists(account_file) or not await cookie_auth(account_file):
180 if not handle:
181 result = _build_login_result(False, "cookie_invalid", "cookie文件不存在或已失效", account_file)
182 return result if return_detail else False
183 kuaishou_logger.info(_msg("🥹", "cookie 失效了,准备重新登录快手创作者平台"))
184 result = await get_ks_cookie(account_file, qrcode_callback=qrcode_callback, headless=headless, cdp_url=cdp_url)
185 return result if return_detail else result["success"]
186
187 result = _build_login_result(True, "cookie_valid", "cookie有效", account_file)
188 return result if return_detail else True
189
190
191 async def get_ks_cookie(
192 account_file,
193 qrcode_callback=None,
194 headless: bool = LOCAL_CHROME_HEADLESS,
195 poll_interval: int = 3,
196 max_checks: int = 100,
197 cdp_url: str | None = None,
198 ):
199 if headless:
200 kuaishou_logger.info(_msg("🖼️", "快手登录将以无头模式运行,小人会输出终端二维码并保存本地二维码图片"))
201
202 async with async_playwright() as playwright:
203 if cdp_url:
204 browser = await playwright.chromium.connect_over_cdp(cdp_url)
205 context = browser.contexts[0] if browser.contexts else await browser.new_context()
206 should_close_context = False
207 else:
208 if LOCAL_CHROME_PATH:
209 browser = await playwright.chromium.launch(headless=headless, executable_path=LOCAL_CHROME_PATH)
210 else:
211 browser = await playwright.chromium.launch(headless=headless, channel="chromium")
212 context = await browser.new_context()
213 should_close_context = True
214 context = await set_init_script(context)
215 qrcode_path = None
216 qrcode_info = None
217 result = _build_login_result(False, "failed", "快手登录失败", account_file)
218 try:
219 page = await context.new_page()
220 await page.goto(KUAISHOU_LOGIN_URL)
221 kuaishou_logger.info(_msg("🧍", "请在浏览器里扫码登录快手,小人正在耐心等待"))
222
223 qrcode_info = await _save_ks_qrcode(page, account_file, qrcode_callback=qrcode_callback)
224 qrcode_path = Path(qrcode_info["image_path"])
225
226 for _ in range(max_checks):
227 if page.url.startswith(KUAISHOU_UPLOAD_URL) or await _is_ks_login_page_gone(page):
228 await context.storage_state(path=account_file)
229 if await cookie_auth(account_file):
230 kuaishou_logger.success(_msg("🥳", "快手扫码登录成功,小人开心收工"))
231 result = _build_login_result(True, "success", "快手扫码登录成功", account_file, qrcode_info, page.url)
232 else:
233 kuaishou_logger.error(_msg("😢", "快手扫码完成了,但 cookie 校验失败"))
234 result = _build_login_result(
235 False,
236 "cookie_invalid",
237 "快手扫码流程结束,但 cookie 校验失败",
238 account_file,
239 qrcode_info,
240 page.url,
241 )
242 return result
243
244 if qrcode_info and await _is_ks_qrcode_expired(page):
245 kuaishou_logger.warning(_msg("😵", "二维码失效了,小人马上去刷新"))
246 refresh_button = page.locator("p.qrcode-refresh").first
247 if await refresh_button.count():
248 await refresh_button.click()
249 await asyncio.sleep(1)
250 qrcode_info = await _save_ks_qrcode(
251 page,
252 account_file,
253 qrcode_path,
254 qrcode_callback=qrcode_callback,
255 )
256 qrcode_path = Path(qrcode_info["image_path"])
257
258 await asyncio.sleep(poll_interval)
259
260 result = _build_login_result(
261 False,
262 "timeout",
263 "等待快手扫码登录超时",
264 account_file,
265 qrcode_info,
266 page.url,
267 )
268 except Exception as exc:
269 result = _build_login_result(False, "failed", str(exc), account_file, current_url=page.url if "page" in locals() else "")
270 finally:
271 if remove_qrcode_file(qrcode_path):
272 kuaishou_logger.info(_msg("🧹", f"临时二维码文件已清理: {qrcode_path}"))
273 if not result["success"]:
274 kuaishou_logger.error(_msg("😢", f"登录失败: {result['message']}"))
275 if should_close_context:
276 await context.close()
277 await browser.close()
278
279 return result
280
281
282 class KSBaseUploader(BaseVideoUploader):
283 def __init__(
284 self,
285 publish_date: datetime | int,
286 account_file,
287 publish_strategy: str | None = None,
288 debug: bool = DEBUG_MODE,
289 headless: bool = LOCAL_CHROME_HEADLESS,
290 ):
291 self.publish_date = publish_date
292 self.account_file = str(account_file)
293 self.publish_strategy = publish_strategy
294 self.debug = debug
295 self.headless = headless
296 self.local_executable_path = LOCAL_CHROME_PATH
297 self.date_format = "%Y-%m-%d %H:%M"
298
299 async def validate_base_args(self):
300 if not os.path.exists(self.account_file):
301 raise RuntimeError(f"cookie文件不存在,请先完成快手登录: {self.account_file}")
302 if not await cookie_auth(self.account_file):
303 raise RuntimeError(f"cookie文件已失效,请先完成快手登录: {self.account_file}")
304
305 if self.publish_strategy is None:
306 self.publish_strategy = (
307 KUAISHOU_PUBLISH_STRATEGY_SCHEDULED
308 if self.publish_date != 0
309 else KUAISHOU_PUBLISH_STRATEGY_IMMEDIATE
310 )
311
312 if self.publish_strategy not in {
313 KUAISHOU_PUBLISH_STRATEGY_IMMEDIATE,
314 KUAISHOU_PUBLISH_STRATEGY_SCHEDULED,
315 }:
316 raise ValueError(f"不支持的发布策略: {self.publish_strategy}")
317
318 if self.publish_strategy == KUAISHOU_PUBLISH_STRATEGY_SCHEDULED:
319 self.publish_date = self.validate_publish_date(self.publish_date)
320 else:
321 self.publish_date = 0
322
323 async def set_schedule_time(self, page: Page, publish_date: datetime):
324 kuaishou_logger.info(_msg("🕒", "小人准备设置定时发布时间"))
325 publish_date_str = publish_date.strftime("%Y-%m-%d %H:%M:%S")
326
327 # 1. 切换到"定时发布"radio (用文本匹配更稳)
328 await page.locator('label.ant-radio-wrapper').filter(has_text="定时发布").click()
329 await asyncio.sleep(2)
330
331 # 2. 点击 picker 打开下拉面板
332 await page.locator('input[placeholder="选择日期时间"]').click()
333 await asyncio.sleep(1)
334
335 # 3. 用 React 兼容的方式直接设置 input 的 value
336 # (ant-design DatePicker 是 controlled component, 必须用 native setter + bubbling event)
337 js_code = """
338 (newValue) => {
339 const input = document.querySelector('input[placeholder="选择日期时间"]');
340 if (!input) return false;
341 const nativeSetter = Object.getOwnPropertyDescriptor(
342 window.HTMLInputElement.prototype, 'value'
343 ).set;
344 nativeSetter.call(input, newValue);
345 input.dispatchEvent(new Event('input', { bubbles: true }));
346 input.dispatchEvent(new Event('change', { bubbles: true }));
347 return true;
348 }
349 """
350 ok = await page.evaluate(js_code, publish_date_str)
351 if not ok:
352 kuaishou_logger.error("❌ 找不到时间选择器输入框")
353 return
354
355 await asyncio.sleep(1)
356 # 4. 按 Enter 确认
357 await page.keyboard.press("Enter")
358 await asyncio.sleep(2)
359 kuaishou_logger.info(f"✅ 定时发布时间已设置为 {publish_date_str}")
360
361 async def close_guide_overlay(self, page: Page) -> bool:
362 joyride_tooltip = page.locator('div[id^="react-joyride-step"] div[role="alertdialog"]')
363
364 # 判断是否显示
365 if await joyride_tooltip.count() > 0 and await joyride_tooltip.first.is_visible():
366 print("检测到 Joyride 引导遮罩,正在关闭...")
367
368 # 点击关闭按钮(X),使用多个可靠特征
369 close_button = page.locator('div[role="alertdialog"]').locator(
370 '[aria-label="Skip"], [data-action="skip"], button[title="Skip"]'
371 )
372
373 await close_button.click(force=True)
374
375 # 等待遮罩消失
376 await joyride_tooltip.wait_for(state="hidden", timeout=5000)
377
378 print("✅ 已关闭 Joyride 遮罩")
379 else:
380 print("未检测到 Joyride 遮罩,继续执行")
381
382
383 class KSVideo(KSBaseUploader):
384 def __init__(
385 self,
386 title,
387 file_path,
388 tags,
389 publish_date: datetime | int,
390 account_file,
391 publish_strategy: str | None = None,
392 debug: bool = DEBUG_MODE,
393 headless: bool = LOCAL_CHROME_HEADLESS,
394 thumbnail_path=None,
395 desc: str | None = None,
396 ):
397 super().__init__(
398 publish_date=publish_date,
399 account_file=account_file,
400 publish_strategy=publish_strategy,
401 debug=debug,
402 headless=headless,
403 )
404 self.title = title
405 self.file_path = file_path
406 self.tags = tags or []
407 self.thumbnail_path = thumbnail_path
408 self.desc = desc or ""
409
410 async def validate_upload_args(self):
411 await self.validate_base_args()
412 if not self.title or not str(self.title).strip():
413 raise ValueError("快手视频上传时,title 是必须的")
414 self.file_path = str(self.validate_video_file(self.file_path))
415 if self.thumbnail_path:
416 self.thumbnail_path = str(self.validate_image_file(self.thumbnail_path))
417
418 async def handle_upload_error(self, page: Page):
419 kuaishou_logger.warning(_msg("😵", "视频上传摔了一跤,小人马上重新上传"))
420 await page.locator('div.progress-div [class^="upload-btn-input"]').set_input_files(self.file_path)
421
422 async def set_thumbnail(self, page: Page):
423 if not self.thumbnail_path:
424 return
425
426 kuaishou_logger.info(_msg("🖼️", "小人准备设置封面"))
427
428 cover_label = page.locator("span").filter(has_text="封面设置")
429 await cover_label.wait_for(state="visible", timeout=30000)
430 await cover_label.locator("xpath=../following-sibling::div[1]").locator('div').nth(0).click()
431
432 modal = page.locator('div[role="document"].ant-modal')
433 await modal.wait_for(state="visible", timeout=30000)
434
435 upload_cover_tab = modal.get_by_text("上传封面", exact=True)
436 await upload_cover_tab.wait_for(state="visible", timeout=10000)
437 await upload_cover_tab.click()
438
439 file_input = modal.locator('input[type="file"]')
440 await file_input.wait_for(state="attached", timeout=30000)
441 await file_input.set_input_files(self.thumbnail_path)
442 await asyncio.sleep(1)
443
444 confirm_button = modal.get_by_role("button", name="确认", exact=True)
445 await confirm_button.wait_for(state="visible", timeout=10000)
446 await confirm_button.click()
447
448 await modal.wait_for(state="hidden", timeout=30000)
449 kuaishou_logger.success(_msg("🥳", "封面已经设置完成"))
450
451 async def upload(self, playwright: Playwright) -> None:
452 kuaishou_logger.info(_msg("🧍", "小人先检查 cookie、视频文件、封面和发布时间"))
453 await self.validate_upload_args()
454 kuaishou_logger.info(_msg("🥳", "上传前检查通过"))
455
456 if self.local_executable_path:
457 browser = await playwright.chromium.launch(
458 headless=self.headless,
459 executable_path=self.local_executable_path,
460 )
461 else:
462 browser = await playwright.chromium.launch(
463 headless=self.headless,
464 channel="chromium",
465 )
466 context = await browser.new_context(storage_state=self.account_file)
467 context = await set_init_script(context)
468
469 upload_success = False
470 try:
471 page = await context.new_page()
472 await page.goto(KUAISHOU_UPLOAD_URL)
473 kuaishou_logger.info(_msg("🏃", f"小人开始搬运视频: {self.title}.mp4"))
474 kuaishou_logger.info(_msg("🧭", "小人正在赶往快手上传主页"))
475 await page.wait_for_url(KUAISHOU_UPLOAD_URL_PATTERN)
476
477 upload_button = page.locator("button[class^='_upload-btn']")
478 await upload_button.wait_for(state="visible", timeout=10000)
479
480 async with page.expect_file_chooser() as fc_info:
481 await upload_button.click()
482 file_chooser = await fc_info.value
483 await file_chooser.set_files(self.file_path)
484
485 await asyncio.sleep(2)
486
487 know_button = page.locator('button[type="button"] span:text("我知道了")').first
488 try:
489 if await know_button.count() and await know_button.is_visible():
490 await know_button.click()
491 except Exception:
492 pass
493
494 await self.close_guide_overlay(page)
495
496 kuaishou_logger.info(_msg("✍️", "小人开始填描述和话题"))
497 await page.get_by_text("描述").locator("xpath=following-sibling::div").click()
498 await page.keyboard.press("Backspace")
499 await page.keyboard.press("Control+KeyA")
500 await page.keyboard.press("Delete")
501 await page.keyboard.type(self.desc or self.title)
502 await page.keyboard.press("Enter")
503
504 for index, tag in enumerate(self.tags[:3], start=1):
505 kuaishou_logger.info(_msg("🏷️", f"小人正在添加第 {index} 个话题: #{tag}"))
506 await page.keyboard.type(f"#{tag} ")
507 await asyncio.sleep(2)
508
509 max_retries = 60
510 retry_count = 0
511 while retry_count < max_retries:
512 try:
513 number = await page.locator("text=上传中").count()
514 if number == 0:
515 kuaishou_logger.success(_msg("🥳", "视频已经传完啦"))
516 break
517
518 if retry_count % 5 == 0:
519 kuaishou_logger.info(_msg("🏃", "小人正在努力上传视频"))
520
521 if await page.locator("text=上传失败").count():
522 await self.handle_upload_error(page)
523
524 await asyncio.sleep(2)
525 except Exception as exc:
526 kuaishou_logger.warning(_msg("😵", f"检查上传状态时出错,小人继续重试: {exc}"))
527 await asyncio.sleep(2)
528 retry_count += 1
529
530 if retry_count == max_retries:
531 kuaishou_logger.warning(_msg("😵", "超过最大重试次数,视频上传可能未完成"))
532
533 await self.set_thumbnail(page)
534
535 if self.publish_strategy == KUAISHOU_PUBLISH_STRATEGY_SCHEDULED and self.publish_date != 0:
536 await self.set_schedule_time(page, self.publish_date)
537
538 while True:
539 try:
540 publish_button = page.get_by_text("发布", exact=True)
541 if await publish_button.count() > 0:
542 await publish_button.click()
543
544 await asyncio.sleep(1)
545 confirm_button = page.get_by_text("确认发布")
546 if await confirm_button.count() > 0:
547 await confirm_button.click()
548
549 await page.wait_for_url(KUAISHOU_MANAGE_URL_PATTERN, timeout=5000)
550 kuaishou_logger.success(_msg("🥳", "视频发布成功,小人开心收工"))
551 break
552 except Exception as exc:
553 kuaishou_logger.info(_msg("🏃", f"小人正在冲刺发布视频: {exc}"))
554 if self.debug:
555 await page.screenshot(full_page=True)
556 await asyncio.sleep(1)
557
558 upload_success = True
559 finally:
560 if upload_success:
561 await context.storage_state(path=self.account_file)
562 kuaishou_logger.success(_msg("🥳", "cookie 更新完毕"))
563 await asyncio.sleep(2)
564 await context.close()
565 await browser.close()
566
567 async def main(self):
568 async with async_playwright() as playwright:
569 await self.upload(playwright)
570
571
572 class KSNote(KSBaseUploader):
573 def __init__(
574 self,
575 image_paths,
576 note,
577 tags,
578 publish_date: datetime | int,
579 account_file,
580 title: str | None = None,
581 publish_strategy: str | None = None,
582 debug: bool = DEBUG_MODE,
583 headless: bool = LOCAL_CHROME_HEADLESS,
584 ):
585 super().__init__(
586 publish_date=publish_date,
587 account_file=account_file,
588 publish_strategy=publish_strategy,
589 debug=debug,
590 headless=headless,
591 )
592 self.image_paths = image_paths
593 self.note = note or ""
594 self.title = title or (self.note[:20] if self.note else "")
595 self.tags = tags or []
596
597 async def validate_upload_args(self):
598 await self.validate_base_args()
599 if not self.title or not str(self.title).strip():
600 raise ValueError("快手图文上传时,title 是必须的")
601 if not self.image_paths:
602 raise ValueError("快手图文上传时,图片是必须的")
603
604 if isinstance(self.image_paths, (str, Path)):
605 self.image_paths = [self.image_paths]
606
607 normalized_image_paths = []
608 for image_path in self.image_paths:
609 normalized_image_paths.append(str(self.validate_image_file(image_path)))
610 self.image_paths = normalized_image_paths
611
612 async def upload_note_content(self, page: Page) -> None:
613 kuaishou_logger.info(_msg("🏃", f"小人开始搬运图文,共 {len(self.image_paths)} 张图片"))
614 kuaishou_logger.info(_msg("🔀", "小人正在切换到图文发布"))
615 await page.locator('div[role="tablist"] div[role="tab"]:has-text("图文")').click()
616 await page.wait_for_timeout(1000)
617
618 kuaishou_logger.info(_msg("📤", "小人正在上传图片"))
619 upload_button = page.locator("button[class^='_upload-btn']").filter(has_text="上传图片")
620 await upload_button.wait_for(state="visible", timeout=10000)
621
622 async with page.expect_file_chooser() as fc_info:
623 await upload_button.click()
624 file_chooser = await fc_info.value
625 await file_chooser.set_files(self.image_paths)
626
627 know_button = page.locator('button[type="button"] span:text("我知道了")').first
628 try:
629 if await know_button.count() and await know_button.is_visible():
630 await know_button.click()
631 except Exception:
632 pass
633
634 await self.close_guide_overlay(page)
635
636 kuaishou_logger.info(_msg("✍️", "小人开始填写图文内容和话题"))
637 await page.get_by_text("描述").locator("xpath=following-sibling::div").click()
638 await page.keyboard.press("Backspace")
639 await page.keyboard.press("Control+KeyA")
640 await page.keyboard.press("Delete")
641 await page.keyboard.type(self.note)
642 await page.keyboard.press("Enter")
643
644 for index, tag in enumerate(self.tags[:3], start=1):
645 kuaishou_logger.info(_msg("🏷️", f"小人正在添加第 {index} 个话题: #{tag}"))
646 await page.keyboard.type(f"#{tag} ")
647 await asyncio.sleep(2)
648
649 max_retries = 60
650 retry_count = 0
651 while retry_count < max_retries:
652 try:
653 number = await page.locator("text=上传中").count()
654 if number == 0:
655 kuaishou_logger.success(_msg("🥳", "图文素材已经传完啦"))
656 break
657
658 if retry_count % 5 == 0:
659 kuaishou_logger.info(_msg("🏃", "小人正在努力上传图文素材"))
660
661 if await page.locator("text=上传失败").count():
662 kuaishou_logger.warning(_msg("😵", "图文素材上传摔了一跤,小人马上重新上传"))
663 await page.locator('div.progress-div [class^="upload-btn-input"]').set_input_files(self.image_paths)
664
665 await asyncio.sleep(2)
666 except Exception as exc:
667 kuaishou_logger.warning(_msg("😵", f"检查图文上传状态时出错,小人继续重试: {exc}"))
668 await asyncio.sleep(2)
669 retry_count += 1
670
671 if retry_count == max_retries:
672 kuaishou_logger.warning(_msg("😵", "超过最大重试次数,图文上传可能未完成"))
673
674 if self.publish_strategy == KUAISHOU_PUBLISH_STRATEGY_SCHEDULED and self.publish_date != 0:
675 await self.set_schedule_time(page, self.publish_date)
676
677 while True:
678 try:
679 publish_button = page.get_by_text("发布", exact=True)
680 if await publish_button.count() > 0:
681 await publish_button.click()
682
683 await asyncio.sleep(1)
684 confirm_button = page.get_by_text("确认发布")
685 if await confirm_button.count() > 0:
686 await confirm_button.click()
687
688 await page.wait_for_url(KUAISHOU_MANAGE_URL_PATTERN, timeout=5000)
689 kuaishou_logger.success(_msg("🥳", "图文发布成功,小人开心收工"))
690 break
691 except Exception as exc:
692 kuaishou_logger.info(_msg("🏃", f"小人正在冲刺发布图文: {exc}"))
693 if self.debug:
694 await page.screenshot(full_page=True)
695 await asyncio.sleep(1)
696
697 async def upload(self, playwright: Playwright) -> None:
698 kuaishou_logger.info(_msg("🧍", "小人先检查 cookie、图片和发布时间"))
699 await self.validate_upload_args()
700 kuaishou_logger.info(_msg("🥳", "图文上传前检查通过"))
701
702 if self.local_executable_path:
703 browser = await playwright.chromium.launch(
704 headless=self.headless,
705 executable_path=self.local_executable_path,
706 )
707 else:
708 browser = await playwright.chromium.launch(
709 headless=self.headless,
710 channel="chromium",
711 )
712 context = await browser.new_context(storage_state=self.account_file)
713 context = await set_init_script(context)
714
715 upload_success = False
716 try:
717 page = await context.new_page()
718 await page.goto(KUAISHOU_UPLOAD_URL)
719 kuaishou_logger.info(_msg("🧭", "小人正在赶往快手图文发布页"))
720 await page.wait_for_url(KUAISHOU_UPLOAD_URL_PATTERN)
721
722 await self.upload_note_content(page)
723 upload_success = True
724 finally:
725 if upload_success:
726 await context.storage_state(path=self.account_file)
727 kuaishou_logger.success(_msg("🥳", "cookie 更新完毕"))
728 await asyncio.sleep(2)
729 await context.close()
730 await browser.close()
731
732 async def main(self):
733 async with async_playwright() as playwright:
734 await self.upload(playwright)
735
735 lines PYTHON