You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中让Playwright等待特定Cookie出现并返回它?

使用Playwright捕获登录后的指定Cookie

以下是实现通过Playwright引导用户登录目标站点,自动捕获指定名称Cookie的Python脚本:

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as playwright:
        browser = await playwright.chromium.launch(headless=False)
        context = await browser.new_context()
        page = await context.new_page()
        await page.goto('https://example.com')
        print('Please log-in')
        while True:
            # 轮询检查Cookie
            for cookie in await context.cookies():
                if cookie['name'] == 'account_cookie':
                    # 捕获到目标Cookie后关闭资源并返回值
                    await context.close()
                    await browser.close()
                    return cookie['value']
            # 添加延迟避免高频查询占用资源
            await asyncio.sleep(1)

if __name__ == "__main__":
    try:
        cookie_value = asyncio.run(main())
        print(f"获取到的Cookie值: {cookie_value}")
    except Exception as e:
        print(f"执行出错: {str(e)}")

优化说明:

  • 新增asyncio.sleep(1),避免无间隔轮询过度消耗系统资源
  • 添加资源清理逻辑,捕获到目标Cookie后及时关闭浏览器上下文与实例,防止资源泄漏
  • 增加异常捕获机制,提升脚本运行稳定性
  • 调整主函数调用方式,更符合Python脚本的通用规范

内容的提问来源于stack exchange,提问作者user23247397

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 18:02:16