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

在asyncio循环中使用Playwright Sync API报错求助

解决Playwright同步API在asyncio循环中运行的错误

错误原因

你当前的代码运行在asyncio事件循环环境中(比如Jupyter Notebook、IPython,或者包含async/await的程序),Playwright同步API不允许在异步循环内执行,必须切换为异步API,或者在纯同步环境运行代码。

解决方案一:使用Playwright异步API

替换为异步版本代码,用asyncio.run()执行:

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as playwright:
        browser = await playwright.chromium.launch()
        page = await browser.new_page()
        await page.goto("https://playwright.dev/")
        await page.screenshot(path="example.png")
        await browser.close()

asyncio.run(main())

解决方案二:在纯同步环境运行原代码

如果想继续用同步API,需要确保代码不在asyncio循环中执行:

  • 如果是在Jupyter/IPython中,使用魔法命令强制在独立进程运行:
    %%script python
    from playwright.sync_api import sync_playwright
    
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch()
        page = browser.new_page()
        page.goto("https://playwright.dev/")
        page.screenshot(path="example.png")
        browser.close()
    
  • 或者将原代码保存为.py文件,直接用Python命令行运行:
    python your_script.py
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 11:53:11