Capture a cell's rendered output as a PNG screenshot. Launches a headless Chromium browser (reused across calls) connected to this server in kiosk mode. Requires `playwright` + its Chromium binary:: ctx.install_packages("playwright") # then once: py
(
self,
target: int | str | NotebookCell | None = None,
*,
timeout_ms: int = 30_000,
as_data_url: bool = False,
save_to: str | PathLike[str] | None = None,
)
| 1346 | # ------------------------------------------------------------------ |
| 1347 | |
| 1348 | async def screenshot( |
| 1349 | self, |
| 1350 | target: int | str | NotebookCell | None = None, |
| 1351 | *, |
| 1352 | timeout_ms: int = 30_000, |
| 1353 | as_data_url: bool = False, |
| 1354 | save_to: str | PathLike[str] | None = None, |
| 1355 | ) -> bytes | str: |
| 1356 | """Capture a cell's rendered output as a PNG screenshot. |
| 1357 | |
| 1358 | Launches a headless Chromium browser (reused across calls) |
| 1359 | connected to this server in kiosk mode. |
| 1360 | |
| 1361 | Requires `playwright` + its Chromium binary:: |
| 1362 | |
| 1363 | ctx.install_packages("playwright") |
| 1364 | # then once: python -m playwright install chromium |
| 1365 | |
| 1366 | Does **not** require `async with`. |
| 1367 | |
| 1368 | Args: |
| 1369 | target: Cell to screenshot. |
| 1370 | |
| 1371 | - `None` — last cell. |
| 1372 | - `int` — cell index (negative OK). |
| 1373 | - `str` — cell ID or name. |
| 1374 | - `NotebookCell` — e.g. `ctx.cells[0]`. |
| 1375 | |
| 1376 | For an object defined by a cell, resolve first:: |
| 1377 | |
| 1378 | cid = ctx.find_cell_defining_object(chart) |
| 1379 | img = await ctx.screenshot(cid) |
| 1380 | |
| 1381 | timeout_ms: Max wait (ms) for the output to be visible. |
| 1382 | as_data_url: Return `data:image/png;base64,...` str |
| 1383 | instead of raw bytes. |
| 1384 | save_to: Also write the PNG to this path. |
| 1385 | |
| 1386 | Returns: |
| 1387 | `bytes` (PNG), or `str` (data URL) if *as_data_url*. |
| 1388 | |
| 1389 | Raises: |
| 1390 | ScreenshotError: Missing playwright, missing browser, |
| 1391 | unknown cell, empty output, or invisible element. |
| 1392 | """ |
| 1393 | from pathlib import Path |
| 1394 | |
| 1395 | from marimo._code_mode.screenshot import ( |
| 1396 | ScreenshotError, |
| 1397 | _ScreenshotSession, |
| 1398 | _to_data_url, |
| 1399 | ) |
| 1400 | from marimo._messaging.context import HTTP_REQUEST_CTX |
| 1401 | |
| 1402 | cell_id = self._resolve_screenshot_target(target) |
| 1403 | |
| 1404 | # Resolve server URL from the current HTTP request context. |
| 1405 | request = HTTP_REQUEST_CTX.get(None) |
no test coverage detected