playwright-python icon indicating copy to clipboard operation
playwright-python copied to clipboard

[BUG] could not use sync api inside jupyter notebook

Open zhuoqiang opened this issue 5 years ago • 9 comments

  • Python: 3.8
  • Playwright: 1.8.0a1
  • OS: MacOS Catalina

the following code failed to run in jupyter notebook envrionment

import playwright.sync_api
with playwright.sync_api.sync_playwright() as api:
    pass

it gives error

---------------------------------------------------------------------------
Error                                     Traceback (most recent call last)
<ipython-input-19-af4d5d3f125f> in <module>
      1 import playwright.sync_api
----> 2 with playwright.sync_api.sync_playwright() as api:
      3     pass

python3.8/site-packages/playwright/sync_api/_context_manager.py in __enter__(self)
     65         self._connection.call_on_object_with_known_name("Playwright", callback_wrapper)
     66 
---> 67         dispatcher_fiber.switch()
     68         playwright = self._playwright
     69         playwright.stop = self.__exit__  # type: ignore

python3.8/site-packages/playwright/sync_api/_context_manager.py in greenlet_main()
     41 
     42             if loop.is_running():
---> 43                 raise Error(
     44                     """It looks like you are using Playwright Sync API inside the asyncio loop.
     45 Please use the Async API instead."""

Error: It looks like you are using Playwright Sync API inside the asyncio loop.
Please use the Async API instead.

zhuoqiang avatar Feb 04 '21 01:02 zhuoqiang

Jupyter notebook uses asyncio event loop, so you should use async api.

pavelfeldman avatar Feb 04 '21 02:02 pavelfeldman

Closing as a dupe for #462

pavelfeldman avatar Mar 02 '21 00:03 pavelfeldman

How can I use async API? What's the code?

rloibman avatar Aug 11 '22 13:08 rloibman

async with async_playwright() as p:
    browser = await p.chromium.launch()
    page = await browser.new_page()
    await page.goto(your url])

fabiofumarola avatar Sep 30 '22 09:09 fabiofumarola

@fabiofumarola

Using async_playwright creates NotImplementedError

from playwright.async_api import async_playwright

async with async_playwright() as p:
    browser = await p.chromium.launch()
    page = await browser.new_page()
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<Connection.run() done, defined at C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\playwright\_impl\_connection.py:240> exception=NotImplementedError()>
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\playwright\_impl\_connection.py", line 247, in run
    await self._transport.connect()
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\playwright\_impl\_transport.py", line 132, in connect
    raise exc
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\playwright\_impl\_transport.py", line 120, in connect
    self._proc = await asyncio.create_subprocess_exec(
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\asyncio\subprocess.py", line 218, in create_subprocess_exec
    transport, protocol = await loop.subprocess_exec(
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 1675, in subprocess_exec
    transport = await self._make_subprocess_transport(
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 498, in _make_subprocess_transport
    raise NotImplementedError
NotImplementedError

asheshstha avatar Dec 31 '22 10:12 asheshstha

I haven't tried running this on Jupyter, but I get the error with Python if I don't install some extra dependencies for Playwright. If you run the command: playwright install-deps This probably would fix this error for Jupyter, since it fixes for me without Jupyter.

demelo-solutions avatar Nov 30 '23 12:11 demelo-solutions

i;m not using async at alll, but if you put code inside a generator, sync_playwright also bails (for no reason)

earonesty avatar May 22 '25 02:05 earonesty

Similar issue here from jupyter lab.

async with async_playwright() as p:
    browser = await p.chromium.launch()
    page = await browser.new_page()
    await page.goto(url)

Produces this error:

---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
Cell In[5], line 1
----> 1 async with async_playwright() as p:
      2     browser = await p.chromium.launch()
      3     page = await browser.new_page()

File [~\anaconda3\envs\scrap\Lib\site-packages\playwright\async_api\_context_manager.py:46](http://localhost:8888/lab/workspaces/auto-o/tree/~/anaconda3/envs/scrap/Lib/site-packages/playwright/async_api/_context_manager.py#line=45), in PlaywrightContextManager.__aenter__(self)
     44 if not playwright_future.done():
     45     playwright_future.cancel()
---> 46 playwright = AsyncPlaywright(next(iter(done)).result())
     47 playwright.stop = self.__aexit__  # type: ignore
     48 return playwright

File [~\anaconda3\envs\scrap\Lib\asyncio\futures.py:199](http://localhost:8888/lab/workspaces/auto-o/tree/~/anaconda3/envs/scrap/Lib/asyncio/futures.py#line=198), in Future.result(self)
    197 self.__log_traceback = False
    198 if self._exception is not None:
--> 199     raise self._exception.with_traceback(self._exception_tb)
    200 return self._result

File [~\anaconda3\envs\scrap\Lib\site-packages\playwright\_impl\_transport.py:120](http://localhost:8888/lab/workspaces/auto-o/tree/~/anaconda3/envs/scrap/Lib/site-packages/playwright/_impl/_transport.py#line=119), in PipeTransport.connect(self)
    117         startupinfo.wShowWindow = subprocess.SW_HIDE
    119     executable_path, entrypoint_path = compute_driver_executable()
--> 120     self._proc = await asyncio.create_subprocess_exec(
    121         executable_path,
    122         entrypoint_path,
    123         "run-driver",
    124         stdin=asyncio.subprocess.PIPE,
    125         stdout=asyncio.subprocess.PIPE,
    126         stderr=_get_stderr_fileno(),
    127         limit=32768,
    128         env=env,
    129         startupinfo=startupinfo,
    130     )
    131 except Exception as exc:
    132     self.on_error_future.set_exception(exc)

File [~\anaconda3\envs\scrap\Lib\asyncio\subprocess.py:224](http://localhost:8888/lab/workspaces/auto-o/tree/~/anaconda3/envs/scrap/Lib/asyncio/subprocess.py#line=223), in create_subprocess_exec(program, stdin, stdout, stderr, limit, *args, **kwds)
    221 loop = events.get_running_loop()
    222 protocol_factory = lambda: SubprocessStreamProtocol(limit=limit,
    223                                                     loop=loop)
--> 224 transport, protocol = await loop.subprocess_exec(
    225     protocol_factory,
    226     program, *args,
    227     stdin=stdin, stdout=stdout,
    228     stderr=stderr, **kwds)
    229 return Process(transport, protocol, loop)

File [~\anaconda3\envs\scrap\Lib\asyncio\base_events.py:1794](http://localhost:8888/lab/workspaces/auto-o/tree/~/anaconda3/envs/scrap/Lib/asyncio/base_events.py#line=1793), in BaseEventLoop.subprocess_exec(self, protocol_factory, program, stdin, stdout, stderr, universal_newlines, shell, bufsize, encoding, errors, text, *args, **kwargs)
   1792     debug_log = f'execute program {program!r}'
   1793     self._log_subprocess(debug_log, stdin, stdout, stderr)
-> 1794 transport = await self._make_subprocess_transport(
   1795     protocol, popen_args, False, stdin, stdout, stderr,
   1796     bufsize, **kwargs)
   1797 if self._debug and debug_log is not None:
   1798     logger.info('%s: %r', debug_log, transport)

File [~\anaconda3\envs\scrap\Lib\asyncio\base_events.py:539](http://localhost:8888/lab/workspaces/auto-o/tree/~/anaconda3/envs/scrap/Lib/asyncio/base_events.py#line=538), in BaseEventLoop._make_subprocess_transport(self, protocol, args, shell, stdin, stdout, stderr, bufsize, extra, **kwargs)
    535 async def _make_subprocess_transport(self, protocol, args, shell,
    536                                      stdin, stdout, stderr, bufsize,
    537                                      extra=None, **kwargs):
    538     """Create subprocess transport."""
--> 539     raise NotImplementedError

NotImplementedError:

guerreroda avatar Jul 29 '25 20:07 guerreroda

Adding a comment here for the benefit of any new users coming to this. Playwright works perfectly fine in jupyter using the async API

Screenshot here showing basic usage:

Image

In this example, the mcr.microsoft.com/playwright:v1.55.0-noble is running in a different container running on port 3010, but I'm sure you can use local playwright as well.

kevcampb avatar Nov 11 '25 09:11 kevcampb