81 lines
3.3 KiB
Python
81 lines
3.3 KiB
Python
|
|
# -*- coding: utf-8 -*-
|
|||
|
|
"""
|
|||
|
|
扫码登录小红书创作者中心
|
|||
|
|
功能:
|
|||
|
|
- 自动打开登录页,展示二维码,等待用户扫码登录
|
|||
|
|
- 登录成功后可获取 cookies 或提示
|
|||
|
|
"""
|
|||
|
|
import time
|
|||
|
|
from playwright.sync_api import sync_playwright
|
|||
|
|
|
|||
|
|
def scan_qrcode():
|
|||
|
|
with sync_playwright() as p:
|
|||
|
|
browser = p.chromium.launch(headless=False)
|
|||
|
|
context = browser.new_context(viewport={"width": 1600, "height": 900})
|
|||
|
|
page = context.new_page()
|
|||
|
|
|
|||
|
|
login_success = False
|
|||
|
|
for i in range(120):
|
|||
|
|
page.goto("https://creator.xiaohongshu.com/new/home")
|
|||
|
|
if "new/home" in page.url:
|
|||
|
|
print("扫码登录成功!")
|
|||
|
|
login_success = True
|
|||
|
|
break
|
|||
|
|
## 等待10s的扫码时间
|
|||
|
|
time.sleep(10)
|
|||
|
|
if not login_success:
|
|||
|
|
print("扫码超时,请重试。")
|
|||
|
|
browser.close()
|
|||
|
|
return
|
|||
|
|
# 只有扫码登录成功后才执行发文流程
|
|||
|
|
try:
|
|||
|
|
import os
|
|||
|
|
# 读取 test 文件夹内容
|
|||
|
|
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')
|
|||
|
|
# 查找所有图片,支持多图上传
|
|||
|
|
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))
|
|||
|
|
if not image_list:
|
|||
|
|
raise Exception("未找到图片文件,请在 test 文件夹中放入图片。")
|
|||
|
|
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()
|
|||
|
|
page.get_by_text("发布图文笔记").click()
|
|||
|
|
time.sleep(1)
|
|||
|
|
# 上传多张图片,定位 input[type='file']
|
|||
|
|
file_input = page.locator("input[type='file']")
|
|||
|
|
file_input.set_input_files(image_list)
|
|||
|
|
time.sleep(1)
|
|||
|
|
# 填写标题
|
|||
|
|
page.get_by_role("textbox", name="填写标题会有更多赞哦~").click()
|
|||
|
|
page.get_by_role("textbox", name="填写标题会有更多赞哦~").fill(title)
|
|||
|
|
time.sleep(1)
|
|||
|
|
# 填写正文
|
|||
|
|
page.get_by_role("textbox").nth(1).click()
|
|||
|
|
page.get_by_role("textbox").nth(1).fill(desc)
|
|||
|
|
time.sleep(1)
|
|||
|
|
# 点击发布
|
|||
|
|
page.get_by_role("button", name="发布").click()
|
|||
|
|
print("已点击发布(多图模式)")
|
|||
|
|
# 发完图文后保存 cookie
|
|||
|
|
try:
|
|||
|
|
from util import save_cookies
|
|||
|
|
cookie_path = os.path.join(base_dir, "cookies.json")
|
|||
|
|
save_cookies(context, cookie_path)
|
|||
|
|
print(f"登录 cookie 已保存到 {cookie_path}")
|
|||
|
|
except Exception as e:
|
|||
|
|
print("保存 cookie 失败:", e)
|
|||
|
|
except Exception as e:
|
|||
|
|
print("自动发文流程异常:", e)
|
|||
|
|
browser.close()
|
|||
|
|
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
scan_qrcode()
|