返回 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.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 xiaohongshu_logger
23
24 XHS_DEFAULT_CREATOR_BASE_URL = "https://creator.xiaohongshu.com"
25 XHS_CREATOR_BASE_URL_ENV = "SAU_XHS_CREATOR_BASE_URL"
26 XHS_PUBLISH_SUCCESS_URL_PATTERN = "**/publish/success?**"
27 XHS_LOGIN_BOX_SELECTOR = "div[class*='login-box']"
28 XHS_LOGIN_SWITCH_SELECTOR = "img.css-wemwzq"
29 XIAOHONGSHU_PUBLISH_STRATEGY_IMMEDIATE = "immediate"
30 XIAOHONGSHU_PUBLISH_STRATEGY_SCHEDULED = "scheduled"
31
32
33 def _build_xhs_creator_url(path: str) -> str:
34 base_url = os.getenv(
35 XHS_CREATOR_BASE_URL_ENV,
36 XHS_DEFAULT_CREATOR_BASE_URL,
37 ).strip().rstrip("/")
38 if not base_url:
39 base_url = XHS_DEFAULT_CREATOR_BASE_URL
40 return f"{base_url}/{path.lstrip('/')}"
41
42
43 def _msg(emoji: str, text: str) -> str:
44 return f"{emoji} {text}"
45
46
47 async def _emit_qrcode_callback(qrcode_callback, payload: dict):
48 if not qrcode_callback:
49 return
50
51 callback_result = qrcode_callback(payload)
52 if inspect.isawaitable(callback_result):
53 await callback_result
54
55
56 def _build_login_result(
57 success: bool,
58 status: str,
59 message: str,
60 account_file: str,
61 qrcode: dict | None = None,
62 current_url: str = "",
63 ) -> dict:
64 return {
65 "success": success,
66 "status": status,
67 "message": message,
68 "account_file": str(account_file),
69 "qrcode": qrcode,
70 "current_url": current_url,
71 }
72
73
74 async def _open_xhs_qrcode_panel(page: Page) -> None:
75 login_box = page.locator(XHS_LOGIN_BOX_SELECTOR).first
76 await login_box.wait_for(state="visible", timeout=30000)
77
78 scan_text = login_box.locator("div:has-text('扫一扫')").first
79 if await scan_text.count():
80 return
81
82 switch_img = login_box.locator(XHS_LOGIN_SWITCH_SELECTOR).first
83 await switch_img.wait_for(state="visible", timeout=10000)
84 await switch_img.click()
85 await login_box.locator("div:has-text('扫一扫')").first.wait_for(state="visible", timeout=10000)
86
87
88 async def _find_xhs_qrcode_locator(page: Page):
89 await _open_xhs_qrcode_panel(page)
90
91 qrcode_img = page.locator('.login-box-container').get_by_text("APP扫一扫登录").filter(visible=True).locator("xpath=..//following-sibling::div//img").nth(0)
92
93 if await qrcode_img.count():
94 return qrcode_img
95
96 raise RuntimeError("未在扫一扫登录区域找到小红书二维码图片")
97
98
99 async def _extract_xhs_qrcode_src(page: Page) -> str:
100 qrcode_img = await _find_xhs_qrcode_locator(page)
101 await qrcode_img.wait_for(state="visible", timeout=30000)
102 qrcode_src = await qrcode_img.get_attribute("src")
103 if not qrcode_src:
104 raise RuntimeError("未获取到小红书登录二维码地址")
105 return qrcode_src
106
107
108 async def _save_xhs_qrcode(
109 page: Page,
110 account_file: str,
111 previous_qrcode_path: Path | None = None,
112 qrcode_callback=None,
113 ) -> dict:
114 qrcode_src = await _extract_xhs_qrcode_src(page)
115 qrcode_path = build_login_qrcode_path(account_file, suffix="xhs_login_qrcode")
116 qrcode_img = await _find_xhs_qrcode_locator(page)
117
118 if qrcode_src.startswith("data:image/"):
119 save_data_url_image(qrcode_src, qrcode_path)
120 else:
121 qrcode_path.parent.mkdir(parents=True, exist_ok=True)
122 await qrcode_img.screenshot(path=str(qrcode_path))
123
124 if previous_qrcode_path and previous_qrcode_path != qrcode_path:
125 if remove_qrcode_file(previous_qrcode_path):
126 xiaohongshu_logger.info(_msg("🧹", f"临时二维码文件已清理: {previous_qrcode_path}"))
127
128 xiaohongshu_logger.info(_msg("🖼️", f"二维码已经准备好啦,已保存到: {qrcode_path}"))
129 qrcode_content = decode_qrcode_from_path(qrcode_path)
130 if qrcode_content:
131 print_terminal_qrcode(qrcode_content, qrcode_path, "小红书APP")
132 else:
133 xiaohongshu_logger.warning(_msg("😵", f"终端没法完整显示二维码,请打开 {qrcode_path} 扫码"))
134
135 qrcode_info = {
136 "image_path": str(qrcode_path),
137 "image_data_url": qrcode_src,
138 }
139 await _emit_qrcode_callback(qrcode_callback, qrcode_info)
140 return qrcode_info
141
142
143 async def _is_xhs_login_completed(page: Page) -> bool:
144 if page.url.startswith(_build_xhs_creator_url("/login")):
145 return False
146
147 login_box = page.locator(XHS_LOGIN_BOX_SELECTOR).first
148 if not await login_box.count():
149 return True
150
151 try:
152 return not await login_box.is_visible()
153 except Exception:
154 return True
155
156
157 async def cookie_auth(account_file):
158 if not os.path.exists(account_file):
159 return False
160
161 async with async_playwright() as playwright:
162 if LOCAL_CHROME_PATH:
163 browser = await playwright.chromium.launch(headless=True, executable_path=LOCAL_CHROME_PATH)
164 else:
165 browser = await playwright.chromium.launch(headless=True, channel="chromium")
166 try:
167 context = await browser.new_context(storage_state=account_file)
168 context = await set_init_script(context)
169 page = await context.new_page()
170 await page.goto(
171 _build_xhs_creator_url(
172 "/publish/publish?from=homepage&target=video"
173 )
174 )
175 await page.wait_for_timeout(3000)
176
177 if page.url.startswith(_build_xhs_creator_url("/login")):
178 xiaohongshu_logger.info(_msg("🥹", "cookie 已失效,得重新登录一下"))
179 return False
180
181 login_box = page.locator(XHS_LOGIN_BOX_SELECTOR).first
182 if await login_box.count():
183 try:
184 if await login_box.is_visible():
185 xiaohongshu_logger.info(_msg("🥹", "页面仍然停留在登录二维码页,按 cookie 失效处理"))
186 return False
187 except Exception:
188 return False
189
190 xiaohongshu_logger.success(_msg("🥳", "cookie 有效"))
191 return True
192 except Exception as exc:
193 xiaohongshu_logger.warning(_msg("😵", f"cookie 校验时出错,按失效处理: {exc}"))
194 return False
195 finally:
196 await browser.close()
197
198
199 async def xiaohongshu_setup(
200 account_file,
201 handle=False,
202 return_detail=False,
203 qrcode_callback=None,
204 headless: bool = LOCAL_CHROME_HEADLESS,
205 ):
206 if not os.path.exists(account_file) or not await cookie_auth(account_file):
207 if not handle:
208 result = _build_login_result(False, "cookie_invalid", "cookie文件不存在或已失效", account_file)
209 return result if return_detail else False
210 xiaohongshu_logger.info(_msg("🥹", "cookie 失效了,准备打开浏览器重新登录"))
211 result = await xiaohongshu_cookie_gen(
212 account_file,
213 qrcode_callback=qrcode_callback,
214 headless=headless,
215 )
216 return result if return_detail else result["success"]
217
218 result = _build_login_result(True, "cookie_valid", "cookie有效", account_file)
219 return result if return_detail else True
220
221
222 async def xiaohongshu_cookie_gen(
223 account_file,
224 qrcode_callback=None,
225 poll_interval: int = 3,
226 max_checks: int = 100,
227 headless: bool = LOCAL_CHROME_HEADLESS,
228 ):
229 if headless:
230 xiaohongshu_logger.info(_msg("🖼️", "小红书登录将以无头模式运行,小人会输出终端二维码并保存本地二维码图片"))
231
232 account_path = Path(account_file)
233 account_path.parent.mkdir(parents=True, exist_ok=True)
234
235 async with async_playwright() as playwright:
236 browser = await playwright.chromium.launch(headless=headless, channel="chromium")
237 context = await browser.new_context()
238 context = await set_init_script(context)
239 qrcode_path = None
240 qrcode_info = None
241 result = _build_login_result(False, "failed", "小红书登录失败", account_file)
242 try:
243 page = await context.new_page()
244 await page.goto(_build_xhs_creator_url("/login"))
245 qrcode_info = await _save_xhs_qrcode(page, account_file, qrcode_callback=qrcode_callback)
246 qrcode_path = Path(qrcode_info["image_path"])
247 xiaohongshu_logger.info(_msg("🧍", "请扫码,小人正在耐心等待登录完成"))
248
249 for _ in range(max_checks):
250 if await _is_xhs_login_completed(page):
251 await asyncio.sleep(2)
252 await context.storage_state(path=account_file)
253 if await cookie_auth(account_file):
254 xiaohongshu_logger.success(_msg("🥳", "小红书扫码登录成功,小人开心收工"))
255 result = _build_login_result(True, "success", "小红书扫码登录成功", account_file, qrcode_info, page.url)
256 else:
257 result = _build_login_result(
258 False,
259 "cookie_invalid",
260 "小红书扫码流程结束,但 cookie 校验失败",
261 account_file,
262 qrcode_info,
263 page.url,
264 )
265 return result
266
267 await asyncio.sleep(poll_interval)
268
269 result = _build_login_result(
270 False,
271 "timeout",
272 "等待小红书扫码登录超时",
273 account_file,
274 qrcode_info,
275 page.url,
276 )
277 except Exception as exc:
278 result = _build_login_result(False, "failed", str(exc), account_file, current_url=page.url if "page" in locals() else "")
279 finally:
280 if remove_qrcode_file(qrcode_path):
281 xiaohongshu_logger.info(_msg("🧹", f"临时二维码文件已清理: {qrcode_path}"))
282 if not result["success"]:
283 xiaohongshu_logger.error(_msg("😢", f"登录失败: {result['message']}"))
284 await context.close()
285 await browser.close()
286 return result
287
288
289 class XiaoHongShuBaseUploader(BaseVideoUploader):
290 def __init__(
291 self,
292 publish_date: datetime | int,
293 account_file,
294 publish_strategy: str = XIAOHONGSHU_PUBLISH_STRATEGY_IMMEDIATE,
295 debug: bool = DEBUG_MODE,
296 headless: bool = LOCAL_CHROME_HEADLESS,
297 ):
298 self.publish_date = publish_date
299 self.account_file = str(account_file)
300 self.publish_strategy = publish_strategy
301 self.debug = debug
302 self.date_format = "%Y年%m月%d日 %H:%M"
303 self.local_executable_path = LOCAL_CHROME_PATH
304 self.headless = headless
305
306 async def validate_base_args(self):
307 if not os.path.exists(self.account_file):
308 raise RuntimeError(f"cookie文件不存在,请先完成小红书登录: {self.account_file}")
309 if not await cookie_auth(self.account_file):
310 raise RuntimeError(f"cookie文件已失效,请先完成小红书登录: {self.account_file}")
311
312 if self.publish_strategy not in {
313 XIAOHONGSHU_PUBLISH_STRATEGY_IMMEDIATE,
314 XIAOHONGSHU_PUBLISH_STRATEGY_SCHEDULED,
315 }:
316 raise ValueError(f"不支持的发布策略: {self.publish_strategy}")
317
318 if self.publish_strategy == XIAOHONGSHU_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_xiaohongshu(self, page: Page, publish_date: datetime):
324 xiaohongshu_logger.info(_msg("🕒", f"小人准备设置定时发布时间: {publish_date.strftime(self.date_format)}"))
325 await page.locator('.custom-switch-card').filter(has_text="定时发布").locator('.d-switch').click()
326 await asyncio.sleep(1)
327 publish_date_hour = publish_date.strftime("%Y-%m-%d %H:%M")
328 time_input = page.locator('.d-datepicker-input-filter input.d-text')
329 await time_input.fill(str(publish_date_hour))
330 await asyncio.sleep(1)
331
332 async def set_location(self, page: Page, location: str = "青岛市"):
333 if not location:
334 return True
335
336 xiaohongshu_logger.info(_msg("📍", f"小人准备设置位置: {location}"))
337 loc_ele = await page.wait_for_selector('div.d-text.d-select-placeholder.d-text-ellipsis.d-text-nowrap')
338 await loc_ele.click()
339 await page.wait_for_timeout(1000)
340 await page.keyboard.type(location)
341 dropdown_selector = 'div.d-popover.d-popover-default.d-dropdown.--size-min-width-large'
342 await page.wait_for_timeout(2000)
343 try:
344 await page.wait_for_selector(dropdown_selector, timeout=3000)
345 except Exception:
346 xiaohongshu_logger.warning(_msg("😵", "位置下拉列表没按预期出现,小人继续按旧逻辑查找"))
347 await page.wait_for_timeout(1000)
348 flexible_xpath = (
349 f'//div[contains(@class, "d-popover") and contains(@class, "d-dropdown")]'
350 f'//div[contains(@class, "d-options-wrapper")]'
351 f'//div[contains(@class, "d-grid") and contains(@class, "d-options")]'
352 f'//div[contains(@class, "name") and text()="{location}"]'
353 )
354 await page.wait_for_timeout(3000)
355 try:
356 location_option = await page.wait_for_selector(
357 flexible_xpath,
358 timeout=3000
359 )
360
361 if not location_option:
362 location_option = await page.wait_for_selector(
363 f'//div[contains(@class, "d-popover") and contains(@class, "d-dropdown")]'
364 f'//div[contains(@class, "d-options-wrapper")]'
365 f'//div[contains(@class, "d-grid") and contains(@class, "d-options")]'
366 f'/div[1]//div[contains(@class, "name") and text()="{location}"]',
367 timeout=2000
368 )
369
370 await location_option.scroll_into_view_if_needed()
371 await location_option.click()
372 xiaohongshu_logger.success(_msg("🥳", f"位置已经设置成 {location}"))
373 return True
374 except Exception as e:
375 xiaohongshu_logger.error(_msg("😢", f"设置位置失败: {e}"))
376 try:
377 all_options = await page.query_selector_all(
378 '//div[contains(@class, "d-popover") and contains(@class, "d-dropdown")]'
379 '//div[contains(@class, "d-options-wrapper")]'
380 '//div[contains(@class, "d-grid") and contains(@class, "d-options")]'
381 '/div'
382 )
383 xiaohongshu_logger.debug(_msg("🧍", f"位置下拉里一共找到 {len(all_options)} 个选项"))
384 for i, option in enumerate(all_options[:3]):
385 option_text = await option.inner_text()
386 xiaohongshu_logger.debug(_msg("🧾", f"候选位置 {i + 1}: {option_text.strip()[:50]}"))
387 except Exception as inner_e:
388 xiaohongshu_logger.debug(_msg("😵", f"读取位置候选列表失败: {inner_e}"))
389 return False
390
391 async def fill_title(self, page: Page) -> None:
392 title_container = page.locator('input[placeholder*="填写标题"]')
393 await title_container.fill(self.title[:20])
394
395 async def fill_desc(self, page: Page) -> None:
396 if not getattr(self, "desc", ""):
397 return
398
399 desc = page.locator('p[data-placeholder*="输入正文描述"]')
400 await desc.click()
401 await page.keyboard.press("Backspace")
402 await page.keyboard.press("Control+KeyA")
403 await page.keyboard.press("Delete")
404 await page.keyboard.type(self.desc)
405 await page.keyboard.press("Enter")
406
407 async def fill_tags(self, page: Page) -> None:
408 if not getattr(self, "tags", None):
409 return
410
411 # 小红书标签上限为 10 个,超过会导致死循环卡住发布
412 max_tags = 10
413 if len(self.tags) > max_tags:
414 xiaohongshu_logger.warning(
415 _msg("🏷️", f"标签数量 {len(self.tags)} 超过小红书上限 {max_tags},只取前 {max_tags} 个: {self.tags[:max_tags]}")
416 )
417 self.tags = self.tags[:max_tags]
418
419 if not getattr(self, "desc", ""):
420 desc = page.locator('p[data-placeholder*="输入正文描述"]')
421 await desc.click()
422
423 for tag in self.tags: # 循环处理所有 tags
424 # 话题候选下拉框依赖小红书联想接口实时返回,网络抖动/无匹配时会等不到。
425 # 标签是可选增强项:等不到候选框就跳过该标签继续,不让整条发布因此失败。
426 try:
427 await page.keyboard.type("#" + tag, delay=30)
428 await page.locator('#creator-editor-topic-container').wait_for(
429 state="visible",
430 timeout=6000
431 )
432 first_item = page.locator('#creator-editor-topic-container .item').first
433 await first_item.wait_for(state="visible", timeout=4000)
434 await first_item.click()
435 except Exception as exc:
436 xiaohongshu_logger.warning(
437 _msg("🏷️", f"话题『{tag}』未出现候选,跳过该标签继续发布: {exc}")
438 )
439 # 清掉已键入但未成词的 "#tag" 文本,避免它残留进正文
440 for _ in range(len("#" + tag)):
441 await page.keyboard.press("Backspace")
442 continue
443
444 async def fill_meta(self, page: Page) -> None:
445 await self.fill_title(page)
446 await self.fill_desc(page)
447 await self.fill_tags(page)
448
449 async def check_original_declaration(self, page: Page) -> None:
450 """勾选原创声明(如果页面上有的话)"""
451 try:
452 # 小红书的原创声明通常是 checkbox 或 switch 组件
453 original_checkbox = page.locator('div.original-declaration checkbox, div.original-declaration input[type="checkbox"], label:has-text("原创") input[type="checkbox"]').first
454 if await original_checkbox.count() and not await original_checkbox.is_checked():
455 await original_checkbox.check()
456 xiaohongshu_logger.success(_msg("✅", "原创声明已勾选"))
457 return
458
459 # 尝试通过文本匹配找到原创声明区域并点击
460 original_text = page.locator('div:has-text("原创声明"), span:has-text("原创声明"), div:has-text("原创"), label:has-text("原创")').first
461 if await original_text.count():
462 await original_text.click()
463 xiaohongshu_logger.success(_msg("✅", "原创声明已勾选"))
464 return
465
466 xiaohongshu_logger.info(_msg("🧾", "未发现原创声明选项,跳过"))
467 except Exception as exc:
468 xiaohongshu_logger.warning(_msg("⚠️", f"勾选原创声明时出错,跳过: {exc}"))
469
470
471 class XiaoHongShuVideo(XiaoHongShuBaseUploader):
472 def __init__(
473 self,
474 title,
475 file_path,
476 tags,
477 publish_date: datetime | int,
478 account_file,
479 thumbnail_path=None,
480 desc: str | None = None,
481 publish_strategy: str = XIAOHONGSHU_PUBLISH_STRATEGY_IMMEDIATE,
482 debug: bool = DEBUG_MODE,
483 headless: bool = LOCAL_CHROME_HEADLESS,
484 ):
485 super().__init__(
486 publish_date=publish_date,
487 account_file=account_file,
488 publish_strategy=publish_strategy,
489 debug=debug,
490 headless=headless,
491 )
492 self.title = title
493 self.file_path = file_path
494 self.tags = tags or []
495 self.thumbnail_path = thumbnail_path
496 self.desc = desc or ""
497
498 async def validate_upload_args(self):
499 await self.validate_base_args()
500 if not self.title or not str(self.title).strip():
501 raise ValueError("视频模式下,title 是必须的")
502
503 self.file_path = str(self.validate_video_file(self.file_path))
504 if self.thumbnail_path:
505 self.thumbnail_path = str(self.validate_image_file(self.thumbnail_path))
506
507 async def handle_upload_error(self, page: Page):
508 xiaohongshu_logger.warning(_msg("😵", "视频上传摔了一跤,小人马上重新上传"))
509 await page.locator('div.progress-div [class^="upload-btn-input"]').set_input_files(self.file_path)
510
511 async def set_thumbnail(self, page: Page, thumbnail_path: str):
512 if not thumbnail_path:
513 return
514
515 xiaohongshu_logger.info(_msg("🖼️", "小人准备设置封面"))
516
517 cover_plugin_title = page.locator("div.cover-plugin-title").filter(has_text="设置封面")
518 cover_upload_dialog = cover_plugin_title.locator(
519 "xpath=ancestor::div[contains(@class, 'cover-plugin-preview')]"
520 ).locator("div.cover > div.default:visible")
521 await cover_upload_dialog.wait_for(state="visible", timeout=30000)
522
523 await cover_upload_dialog.click(force=True)
524
525 modal = page.locator("div.d-modal.cover-modal")
526 await modal.wait_for(state="visible", timeout=30000)
527
528 file_input = modal.locator('input[type="file"][accept*="image"]').first
529 await file_input.wait_for(state="attached", timeout=10000)
530 await file_input.set_input_files(thumbnail_path)
531 await page.wait_for_timeout(2000)
532
533 confirm_button = modal.locator("button.mojito-button").filter(has_text="确定").first
534 await confirm_button.wait_for(state="visible", timeout=10000)
535 await confirm_button.click()
536
537 await modal.wait_for(state="hidden", timeout=30000)
538 xiaohongshu_logger.success(_msg("🥳", "封面已经设置完成"))
539
540 async def upload_video_content(self, page: Page) -> None:
541 xiaohongshu_logger.info(_msg("🏃", f"小人开始搬运视频: {self.title}.mp4"))
542 xiaohongshu_logger.info(_msg("🧭", "小人正在赶往视频发布页"))
543 publish_url = _build_xhs_creator_url(
544 "/publish/publish?from=homepage&target=video"
545 )
546 await page.goto(publish_url)
547 await page.wait_for_url(publish_url)
548 await page.locator("div[class^='upload-content'] input[class='upload-input']").set_input_files(self.file_path)
549
550 while True:
551 try:
552 upload_input = await page.wait_for_selector('input.upload-input', timeout=3000)
553 preview_new = await upload_input.query_selector(
554 'xpath=following-sibling::div[contains(@class, "preview-new")]')
555 if preview_new:
556 # 获取整个预览区域的文本,更鲁棒地判断上传状态
557 all_text = await preview_new.inner_text()
558 upload_success = any(keyword in all_text for keyword in ['上传成功', '分辨率', '重新上传', '编辑封面', '已上传', '已选择', '100%'])
559
560 if not upload_success:
561 # 检查是否有特定的状态码或百分比
562 stage_elements = await preview_new.query_selector_all('div.stage')
563 for stage in stage_elements:
564 text_content = await page.evaluate('(element) => element.textContent', stage)
565 if '上传成功' in text_content or '分辨率' in text_content:
566 upload_success = True
567 break
568
569 if upload_success:
570 xiaohongshu_logger.success(_msg("🥳", "视频已经传完啦"))
571 break
572
573 if self.debug:
574 normalized_text = all_text.strip().replace("\n", " ")
575 xiaohongshu_logger.debug(_msg("🧍", f"预览区域内容: {normalized_text}"))
576 xiaohongshu_logger.debug(_msg("🧍", "还没看到上传成功标识,小人继续等一会"))
577 else:
578 # 尝试检查标题输入框是否已经出现,如果是,说明已经进入编辑状态
579 title_container = page.locator('input[placeholder*="填写标题"]')
580 if await title_container.count() > 0 and await title_container.is_visible():
581 xiaohongshu_logger.success(_msg("🥳", "虽然没看到预览区,但标题框出来了,小人继续"))
582 break
583 xiaohongshu_logger.debug(_msg("🧍", "还没拿到预览区域,小人继续等一会"))
584 except Exception as e:
585 xiaohongshu_logger.debug(_msg("😵", f"上传状态还没稳定下来,小人继续观察: {e}"))
586 await asyncio.sleep(2)
587
588 xiaohongshu_logger.info(_msg("✍️", "小人开始填标题、描述和话题"))
589 await self.fill_meta(page)
590
591 await self.set_thumbnail(page, self.thumbnail_path)
592
593 # await self.set_location(page, "青岛市")
594
595 await self.check_original_declaration(page)
596
597 if self.publish_strategy == XIAOHONGSHU_PUBLISH_STRATEGY_SCHEDULED and self.publish_date != 0:
598 await self.set_schedule_time_xiaohongshu(page, self.publish_date)
599
600 while True:
601 try:
602 if self.publish_strategy == XIAOHONGSHU_PUBLISH_STRATEGY_SCHEDULED:
603 await page.locator('button:has-text("定时发布")').click()
604 else:
605 await page.locator('button:has-text("发布")').click()
606 await page.wait_for_url(
607 XHS_PUBLISH_SUCCESS_URL_PATTERN,
608 timeout=3000
609 )
610 xiaohongshu_logger.success(_msg("🥳", "视频发布成功,小人开心收工"))
611 break
612 except Exception:
613 xiaohongshu_logger.info(_msg("🏃", "小人正在冲刺发布视频"))
614 if self.debug:
615 await page.screenshot(full_page=True)
616 await asyncio.sleep(0.5)
617
618 async def upload(self, playwright: Playwright) -> None:
619 xiaohongshu_logger.info(_msg("🧍", "小人先检查 cookie、视频文件、封面和发布时间"))
620 await self.validate_upload_args()
621 xiaohongshu_logger.info(_msg("🥳", "上传前检查通过"))
622 browser = await playwright.chromium.launch(headless=self.headless, channel="chromium")
623 context = await browser.new_context(
624 permissions=["geolocation"],
625 storage_state=self.account_file,
626 )
627 context = await set_init_script(context)
628
629 try:
630 page = await context.new_page()
631 await self.upload_video_content(page)
632 await context.storage_state(path=self.account_file)
633 xiaohongshu_logger.success(_msg("🥳", "cookie 更新完毕"))
634 finally:
635 await context.close()
636 await browser.close()
637
638 async def xiaohongshu_upload_video(self):
639 async with async_playwright() as playwright:
640 await self.upload(playwright)
641
642 async def main(self):
643 await self.xiaohongshu_upload_video()
644
645
646 class XiaoHongShuNote(XiaoHongShuBaseUploader):
647 def __init__(
648 self,
649 image_paths,
650 note,
651 tags,
652 publish_date: datetime | int,
653 account_file,
654 title: str | None = None,
655 desc: str | None = None,
656 publish_strategy: str = XIAOHONGSHU_PUBLISH_STRATEGY_IMMEDIATE,
657 debug: bool = DEBUG_MODE,
658 headless: bool = LOCAL_CHROME_HEADLESS,
659 ):
660 super().__init__(
661 publish_date=publish_date,
662 account_file=account_file,
663 publish_strategy=publish_strategy,
664 debug=debug,
665 headless=headless,
666 )
667 self.image_paths = image_paths
668 self.note = note or ""
669 self.tags = tags or []
670 self.desc = desc if desc is not None else self.note
671 self.title = title or ((self.desc or self.note)[:20] if (self.desc or self.note) else "")
672
673 async def validate_upload_args(self):
674 await self.validate_base_args()
675 if not self.image_paths:
676 raise ValueError("图文模式下,图片是必须的")
677 if not self.title or not str(self.title).strip():
678 raise ValueError("图文模式下,title 是必须的")
679
680 if isinstance(self.image_paths, (str, Path)):
681 self.image_paths = [self.image_paths]
682
683 normalized_image_paths = []
684 for image_path in self.image_paths:
685 normalized_image_paths.append(str(self.validate_image_file(image_path)))
686 self.image_paths = normalized_image_paths
687
688 async def upload_note_content(self, page: Page) -> None:
689 xiaohongshu_logger.info(_msg("🏃", f"小人开始搬运图文,共 {len(self.image_paths)} 张图片"))
690 xiaohongshu_logger.info(_msg("🧭", "小人正在赶往图文发布页"))
691 publish_url = _build_xhs_creator_url(
692 "/publish/publish?from=homepage&target=image"
693 )
694 await page.goto(publish_url)
695 await page.wait_for_url(publish_url)
696
697 upload_input = page.locator('input[type="file"][accept*="image"]').first
698 if not await upload_input.count():
699 upload_input = page.locator("div[class^='upload-content'] input[class='upload-input']").first
700
701 await upload_input.wait_for(state="attached", timeout=30000)
702 xiaohongshu_logger.info(_msg("📤", "小人正在上传图片"))
703 await upload_input.set_input_files(self.image_paths)
704
705 while True:
706 try:
707 title_container = page.locator('input[placeholder*="填写标题"]').first
708 await title_container.wait_for(state="visible", timeout=3000)
709 xiaohongshu_logger.success(_msg("🥳", "图文素材已经传完,可以开始填写内容了"))
710 break
711 except Exception:
712 xiaohongshu_logger.debug(_msg("🧍", "图文素材还在上传,小人继续等一会"))
713 await asyncio.sleep(1)
714
715 xiaohongshu_logger.info(_msg("✍️", "小人开始填标题、描述和话题"))
716 await self.fill_meta(page)
717
718 await self.check_original_declaration(page)
719
720 if self.publish_strategy == XIAOHONGSHU_PUBLISH_STRATEGY_SCHEDULED and self.publish_date != 0:
721 await self.set_schedule_time_xiaohongshu(page, self.publish_date)
722
723 while True:
724 try:
725 if self.publish_strategy == XIAOHONGSHU_PUBLISH_STRATEGY_SCHEDULED:
726 await page.locator('button:has-text("定时发布")').click()
727 else:
728 await page.locator('button:has-text("发布")').click()
729 await page.wait_for_url(
730 XHS_PUBLISH_SUCCESS_URL_PATTERN,
731 timeout=3000
732 )
733 xiaohongshu_logger.success(_msg("🥳", "图文发布成功,小人开心收工"))
734 break
735 except Exception:
736 xiaohongshu_logger.info(_msg("🏃", "小人正在冲刺发布图文"))
737 if self.debug:
738 await page.screenshot(full_page=True)
739 await asyncio.sleep(0.5)
740
741 async def upload(self, playwright: Playwright) -> None:
742 xiaohongshu_logger.info(_msg("🧍", "小人先检查 cookie、图片和发布时间"))
743 await self.validate_upload_args()
744 xiaohongshu_logger.info(_msg("🥳", "图文上传前检查通过"))
745 browser = await playwright.chromium.launch(headless=self.headless, channel="chromium")
746 context = await browser.new_context(
747 permissions=["geolocation"],
748 storage_state=self.account_file,
749 )
750 context = await set_init_script(context)
751
752 try:
753 page = await context.new_page()
754 await self.upload_note_content(page)
755 await context.storage_state(path=self.account_file)
756 xiaohongshu_logger.success(_msg("🥳", "cookie 更新完毕"))
757 finally:
758 await context.close()
759 await browser.close()
760
761 async def xiaohongshu_upload_note(self):
762 async with async_playwright() as playwright:
763 await self.upload(playwright)
764
765 async def main(self):
766 await self.xiaohongshu_upload_note()
767
767 lines PYTHON