playwright坑点记录
Jupyter NoteBook的运行
使from playwright.sync_api import sync_playwright在 Jupyter NoteBook 中运行时,直接运行以下代码会报错:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("http://www.baidu.com")
page.screenshot(path="./example.png")
browser.close()错误信息:
---------------------------------------------------------------------------
Error Traceback (most recent call last)
Cell In[1], line 4
1 """QuickStart"""
2 from playwright.sync_api import sync_playwright
----> 4 with sync_playwright() as p:
5 browser = p.chromium.launch()
6 page = browser.new_page()
File f:\env\miniconda3\envs\python12\Lib\site-packages\playwright\sync_api\_context_manager.py:47, in PlaywrightContextManager.__enter__(self)
45 self._own_loop = True
46 if self._loop.is_running():
---> 47 raise Error(
48 """It looks like you are using Playwright Sync API inside the asyncio loop.
49 Please use the Async API instead."""
50 )
52 # Create a new fiber for the protocol dispatcher. It will be pumping events
53 # until the end of times. We will pass control to that fiber every time we
54 # block while waiting for a response.
55 def greenlet_main() -> None:
Error: It looks like you are using Playwright Sync API inside the asyncio loop.
Please use the Async API instead.这是因为 Jupyter Notebook 本身运行在一个 asyncio 事件循环 中,这导致了与 Playwright 同步 API 的冲突
解决办法:
将这份代码保存为.py文件
版权声明:
本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自
soap的会员制餐厅!
喜欢就支持一下吧