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

ImportError:无法从playwright.async_api导入sync_playwright求助

解决ImportError: cannot import name 'sync_playwright' from 'playwright.async_api'

错误核心原因

sync_playwright 是Playwright同步API的入口方法,不属于playwright.async_api模块,你搞错了导入路径。

直接修复代码

修正导入语句和调用方式:

# 从同步API模块导入正确的方法
from playwright.sync_api import sync_playwright, Playwright

# 注意sync_playwright是函数,必须加()调用
with sync_playwright() as p:
    browser = p.chromium.launch(headless=False, slow_mo=50)
    page = browser.new_page()
    # goto需要完整URL,补充http/https协议头
    page.goto('https://google.com')
    # 可选:显式关闭浏览器(with块结束会自动清理,显式操作更稳妥)
    browser.close()

环境依赖排查(修复后仍报错时执行)

  • 卸载冲突依赖:
    pip3 uninstall -y playwright pytest-playwright
    
  • 重新安装稳定版本:
    pip3 install playwright pytest-playwright
    playwright install
    
  • 验证Python环境一致性:用which python3和which pip3检查,确保脚本使用的解释器与pip3对应同一个环境

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:58:14