Files
ai_xhs/use_cookie.py
2025-12-08 15:27:00 +08:00

87 lines
3.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""
自动发文脚本test.py
功能:
"""
import os
import json
from playwright.sync_api import sync_playwright
def get_test_content():
base_dir = os.path.dirname(os.path.abspath(__file__))
test_dir = os.path.join(base_dir, 'test')
title_path = os.path.join(test_dir, 'title.txt')
desc_path = os.path.join(test_dir, 'desc.txt')
with open(title_path, 'r', encoding='utf-8') as f:
title = f.read().strip()
with open(desc_path, 'r', encoding='utf-8') as f:
desc = f.read().strip()
# 查找所有图片,支持多图上传
exts = ['.jpg', '.jpeg', '.png', '.bmp', '.gif']
image_list = []
for fname in os.listdir(test_dir):
if any(fname.lower().endswith(ext) for ext in exts):
image_list.append(os.path.join(test_dir, fname))
return title, desc, image_list
def auto_publish_xhs(title, desc, image_path):
# 自动读取扫码登录保存的 cookie
base_dir = os.path.dirname(os.path.abspath(__file__))
cookie_path = os.path.join(base_dir, "cookies.json")
if not os.path.exists(cookie_path):
print("未找到 cookies.json请先扫码登录生成 cookie")
return
with open(cookie_path, 'r', encoding='utf-8') as f:
cookies = json.load(f)
import time
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
context = browser.new_context(viewport={"width": 1600, "height": 900})
context.add_cookies(cookies)
page = context.new_page()
# 进入主页cookie生效后自动登录
page.goto("https://creator.xiaohongshu.com/new/home")
time.sleep(2)
# 进入图文发布页面
page.get_by_text("发布图文笔记").click()
time.sleep(1)
# 上传多张图片,定位 input[type='file']
try:
file_input = page.locator("input[type='file']")
file_input.set_input_files(image_path)
print('图片已上传')
except Exception as e:
print('图片上传控件异常:', e)
time.sleep(1)
# 填写标题
try:
page.get_by_role("textbox", name="填写标题会有更多赞哦~").click()
page.get_by_role("textbox", name="填写标题会有更多赞哦~").fill(title)
except Exception as e:
print('标题控件异常:', e)
time.sleep(1)
# 填写正文
try:
page.get_by_role("textbox").nth(1).click()
page.get_by_role("textbox").nth(1).fill(desc)
except Exception as e:
print('正文控件异常:', e)
time.sleep(1)
# 点击发布
try:
page.get_by_role("button", name="发布").click()
print('已点击发布(多图模式)')
except Exception as e:
print('发布按钮异常:', e)
time.sleep(2)
print('发文流程结束,请检查小红书后台是否发布成功')
browser.close()
if __name__ == '__main__':
title, desc, image_list = get_test_content()
if not image_list:
print('未找到图片文件请将图片放入test文件夹')
else:
auto_publish_xhs(title, desc, image_list)