This commit is contained in:
熊潇 2025-05-03 18:01:54 +08:00
parent 2718d24977
commit 8f0b81ebd9

23
app.py
View File

@ -111,13 +111,15 @@ async def sign(uri: str, data: Dict[str, Any], a1: str, web_session: str) -> Dic
if a1 != global_a1: if a1 != global_a1:
await setCookie(a1) # Ensure setCookie is awaited properly await setCookie(a1) # Ensure setCookie is awaited properly
# 执行 JavaScript 函数 # 执行 JavaScript 函数
# localStorage.getItem("b1")
b1 = await context_page.evaluate("() => localStorage.getItem('b1')") b1 = await context_page.evaluate("() => localStorage.getItem('b1')")
b1b1 = await context_page.evaluate("() => localStorage.getItem('b1b1')") b1b1 = await context_page.evaluate("() => localStorage.getItem('b1b1')")
encrypt_params = await context_page.evaluate("([url, data]) => window._webmsxyw(url, data)", [uri, data]) encrypt_params = await context_page.evaluate("([url, data]) => window._webmsxyw(url, data)", [uri, data])
if not encrypt_params or not isinstance(encrypt_params, dict): if not encrypt_params or not isinstance(encrypt_params, dict):
raise HTTPException(status_code=500, detail="Failed to retrieve encryption parameters") raise HTTPException(status_code=500, detail="Failed to retrieve encryption parameters")
return { return {
"x-s": encrypt_params["X-s"], "x-s": encrypt_params["X-s"],
"x-t": str(encrypt_params["X-t"]), "x-t": str(encrypt_params["X-t"]),
@ -125,8 +127,23 @@ async def sign(uri: str, data: Dict[str, Any], a1: str, web_session: str) -> Dic
"b1b1": b1b1, "b1b1": b1b1,
} }
except Exception as e: except Exception as e:
print(f"Error during sign operation: {e}") # 检测页面崩溃错误并重新初始化
raise HTTPException(status_code=500, detail=str(e)) if "Target crashed" in str(e):
print("页面崩溃,正在重新初始化浏览器上下文和页面...")
try:
browser_context, context_page = await get_context_page(playwright_instance, "stealth.min.js")
await context_page.goto("https://www.xiaohongshu.com")
await asyncio.sleep(5)
await context_page.reload()
await asyncio.sleep(1)
# 重试签名操作
return await sign(uri, data, a1, web_session)
except Exception as reinit_error:
print(f"重新初始化失败: {reinit_error}")
raise HTTPException(status_code=500, detail="Failed to recover from page crash")
else:
print(f"Error during sign operation: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/sign") @app.post("/sign")