Python交互式模式运行Playwright报错:'PlaywrightContextManager'无chromium属性
解决Playwright交互式模式下
AttributeError: 'PlaywrightContextManager' object has no attribute 'chromium'问题 问题场景
使用Playwright脚本爬取页面时可正常运行,但在Python交互式环境中执行以下代码时触发错误:
交互式执行代码:
>>> from playwright.sync_api import Playwright, sync_playwright, expect >>> playwright = sync_playwright() >>> browser = playwright.chromium.launch(headless=False)
报错信息:
Traceback (most recent call last): File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\idlelib\run.py", line 578, in runcode exec(code, self.locals) File "<pyshell#2>", line 1, in <module> AttributeError: 'PlaywrightContextManager' object has no attribute 'chromium'
解决方案
方法1:在交互式环境中使用with语句(推荐)
和脚本中的写法一致,通过with语句自动获取Playwright实例并管理上下文:
from playwright.sync_api import sync_playwright with sync_playwright() as playwright: # 启动浏览器 browser = playwright.chromium.launch(headless=False) # 创建上下文和页面 context = browser.new_context() page = context.new_page() page.goto("https://www.wikipedia.org/") # 执行你的爬取操作... # 清理资源 context.close() browser.close()
方法2:手动操作上下文管理器
如果不想用with语句,可以手动调用上下文管理器的__enter__()方法获取Playwright实例,用完后再调用__exit__()清理:
from playwright.sync_api import sync_playwright # 获取上下文管理器 playwright_manager = sync_playwright() # 进入上下文,获取Playwright实例 playwright = playwright_manager.__enter__() # 启动浏览器并执行操作 browser = playwright.chromium.launch(headless=False) context = browser.new_context() page = context.new_page() page.goto("https://www.wikipedia.org/") # 执行操作后清理资源 context.close() browser.close() # 退出上下文 playwright_manager.__exit__(None, None, None)
原因说明
sync_playwright()返回的是PlaywrightContextManager对象,而非直接的Playwright实例。只有通过with语句自动触发__enter__()方法,或者手动调用该方法,才能得到包含chromium、firefox等浏览器驱动属性的Playwright实例。脚本中的with语句会自动处理上下文的进入和退出,而交互式模式下直接赋值playwright = sync_playwright()得到的是管理器对象,自然没有chromium属性,导致报错。
内容的提问来源于stack exchange,提问作者Himanshu Poddar
相关产品推荐
相关产品推荐

