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

56 lines
2.3 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.

from flask import Flask, render_template, request, session
from playwright.sync_api import sync_playwright
import os
import time
app = Flask(__name__)
app.secret_key = 'your_secret_key'
@app.route('/')
def index():
return render_template('login.html')
@app.route('/send_code', methods=['POST'])
def send_code():
phone = request.form['phone']
session['phone'] = phone
# 用 Playwright 打开页面并点击发送验证码
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
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.wait_for_timeout(15000) # 等待用户手动输入验证码
page.get_by_text("发送验证码").click()
# 保存 context 到磁盘,后续用
time.sleep(20) # 确保操作完成
context.storage_state(path="state.json")
# browser.close()
return "验证码已发送,请查收手机短信!<a href='/'>返回</a>"
@app.route('/login', methods=['POST'])
def login():
code = request.form['code']
phone = session.get('phone')
# 用 Playwright继续登录
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = p.chromium.launch_persistent_context(user_data_dir=".", storage_state="state.json")
page = context.pages[0] if context.pages else context.new_page()
page.goto("https://creator.xiaohongshu.com/login?source=&redirectReason=401&lastUrl=%252Fnew%252Fhome")
# 填写验证码并登录
page.wait_for_selector('input[placeholder*="验证码"]', timeout=15000)
vcode_box = page.locator('input[placeholder*="验证码"]')
vcode_box.fill(code)
page.get_by_role("button", name="登 录").click()
# 等待跳转
page.wait_for_url("**/new/home", timeout=20000)
# 保存 cookies
context.storage_state(path="cookies.json")
browser.close()
return "登录成功cookie已保存<a href='/'>返回</a>"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)