Files
ai_xhs/phone_num.py

104 lines
4.6 KiB
Python
Raw Permalink Normal View History

2025-12-08 15:27:00 +08:00
# -*- coding: utf-8 -*-
"""
手机号登录小红书创作者中心
功能
- 自动打开登录页等待用户手机号登录
- 登录成功后可获取 cookies 或提示
"""
import time
from playwright.sync_api import sync_playwright
def scan_qrcode():
with sync_playwright() as p:
import getpass
browser = p.chromium.launch(headless=False)
context = browser.new_context(viewport={"width": 1600, "height": 900})
page = context.new_page()
# 1. 让用户输入手机号和验证码
phone = input("请输入手机号: ")
page.goto("https://creator.xiaohongshu.com/login?source=&redirectReason=401&lastUrl=%252Fnew%252Fhome")
page.get_by_role("textbox", name="手机号").click()
page.get_by_role("textbox", name="手机号").fill(phone)
page.get_by_text("发送验证码").click()
code = input("请输入收到的验证码: ")
# 等待验证码输入框出现,兼容多种写法
try:
# 先尝试常规定位
page.wait_for_selector('input[placeholder*="验证码"], input[name*="code"], input[type="text"]', timeout=15000)
# 优先用 placeholder 包含“验证码”
if page.query_selector('input[placeholder*="验证码"]'):
vcode_box = page.locator('input[placeholder*="验证码"]')
elif page.query_selector('input[name*="code"]'):
vcode_box = page.locator('input[name*="code"]')
else:
# 兜底用第2个文本框
vcode_box = page.locator('input[type="text"]').nth(1)
vcode_box.click()
vcode_box.fill(code)
except Exception as e:
print("验证码输入框定位失败,请检查页面结构或手动调整定位方式。", e)
browser.close()
return
page.get_by_role("button", name="登 录").click()
# 等待跳转到主页
for i in range(30):
time.sleep(2)
if "new/home" in page.url:
print("手机号登录成功!")
break
else:
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()