Python获取Twitter auth_token:解决cookies索引不固定问题
用Playwright异步可靠获取Twitter的auth_token
直接通过遍历cookies数组、匹配name字段的方式定位auth_token,完全规避固定索引的不稳定问题,以下是具体实现代码:
import asyncio from playwright.async_api import async_playwright async def fetch_and_save_auth_token(): async with async_playwright() as p: # 启动浏览器,headless设为False方便调试,上线可改为True browser = await p.chromium.launch(headless=False) context = await browser.new_context() page = await context.new_page() # 访问Twitter,需确保已完成登录流程(可手动登录或加载已保存的上下文) await page.goto("https://twitter.com") # 获取当前上下文的所有cookies all_cookies = await context.cookies() # 遍历cookies,精准匹配name为auth_token的项 auth_token = None for cookie in all_cookies: if cookie.get("name") == "auth_token": auth_token = cookie.get("value") break # 找到token后写入文件(用你已掌握的写入逻辑即可) if auth_token: with open("auth_token.txt", "w", encoding="utf-8") as f: f.write(auth_token) print("auth_token已成功保存到文件") else: print("未找到auth_token,请确认已完成Twitter登录") await browser.close() asyncio.run(fetch_and_save_auth_token())
关键说明:
- 遍历匹配
name字段是最稳定的方案,不受cookies数组排序变化影响 - 可以用列表推导式简化查找逻辑,一行搞定:
auth_token = next((cookie["value"] for cookie in all_cookies if cookie["name"] == "auth_token"), None) - 务必保证获取cookies前已完成登录,否则
auth_token不会出现在cookies列表中
内容的提问来源于stack exchange,提问作者Noob
相关产品推荐
相关产品推荐

