如何在Python中让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
相关产品推荐
相关产品推荐

