# AgentSandbox.host > Browser testing at scale with Playwright and Selenium: setup in Python and Node.js, Docker images, Selenium Grid, parallel runs, sharding and flaky tests. --- # How to fix flaky browser tests in Playwright and Selenium URL: https://www.agentsandbox.host/p/fix-flaky-browser-tests/ Author: AgentSandbox.host editors Published: 2026-11-26 Updated: 2026-11-26 Fix flaky browser tests by first proving they are flaky (run them many times), then separating environment trouble from test bugs, then removing the cause, usually timing, shared state or overloaded machines. Retries and traces find flaky tests; auto-waiting, isolation and fewer workers fix them. A flaky browser test is one that passes and fails on the same code. Playwright Test gives the category its own name: "flaky: tests that failed on the first run, but passed when retried" ([Playwright retries](https://playwright.dev/docs/test-retries), read 2026-11-26). Fixing flakiness is a four-step job: prove it, find whose fault it is, read what happened, and remove the cause. ## Step 1: How do I prove a test is flaky? Prove a test is flaky by running it many times on unchanged code. Playwright Test has a flag for it: `--repeat-each `, "Run each test `N` times" ([Playwright command line](https://playwright.dev/docs/test-cli), read 2026-11-26). ``` npx playwright test tests/checkout.spec.ts --repeat-each=20 --workers=4 ``` 1. Use the same worker count as the machine where it flakes; load is part of the cause. 2. Add `--shuffle` to change the order; a test that only fails after another test is a shared-state bug. 3. In CI, `--fail-on-flaky-tests` makes the run fail "if any test is flagged as flaky", so flaky passes stop counting as green. ## Step 2: Is it the test or the environment? Decide this before touching the test: a crashed browser, a full disk or a registry that timed out make a correct test fail, and rewriting the test will not help. There are three ways to keep the two kinds of failure apart: 1. **Promigence's validity report.** Promigence returns a report after every run that classifies each sandbox's outcome (Promigence FAQ, read 2026-11-26). Its quickstart lists what the report holds: completed runs, task failures, environment failures and the cost, where a task failure means "your command exited non-zero" and an environment failure "never counts against your agent" (the quickstart, read 2026-11-26). Its errors page gives each kind its own exit code, 3 for "Environment failure: the environment failed, not your command" and 4 for "Task failure: your command failed", and says an environment failure is "kept out of your result and retried once before hand-over" (the errors page, read 2026-11-26). To rerun one result by hand, `promigence run report --sandbox --repro` prints the command that reproduces it, and its replay command, `promigence run replay`, runs the environment's share of a run again as new sandboxes billed under the run's cap (Promigence FAQ). The security page adds that "A failed sandbox's state is kept for up to 7 days by default", so the sandbox where a test went wrong can be reopened and looked at (the security page, read 2026-11-26). The command for that is `promigence run open`. 2. **Playwright's own signals.** When a test fails, "Playwright Test will discard the entire worker process along with the browser and will start a new one" (Playwright retries, read 2026-11-26). A browser that never launched points at the environment; `DEBUG=pw:browser` logs the launch, which Playwright calls "helpful while debugging Error: Failed to launch browser errors" ([Playwright CI](https://playwright.dev/docs/ci), read 2026-11-26). 3. **Your own bookkeeping.** Record the machine, container id and exit reason with every result, and compare failure rates per machine. A test that fails on one host and nowhere else is an environment problem. Other hosted services expose the environment side through their own errors and states, which you can log beside each test result (read 2026-11-26): - **AWS:** Amazon Bedrock AgentCore Runtime stops a session whose compute "is deemed unhealthy based on health checks", and a call that arrives while a session is being set up or torn down gets a retryable HTTP 409 (AgentCore sessions documentation). - **Daytona:** a command that fails returns its non-zero `exitCode` in the response, problems on the sandbox's side are raised as a `DaytonaError` (Daytona process documentation), and a sandbox in the Error state "needs to be recovered" (Daytona sandboxes documentation). - **E2B:** the SDK raises `SandboxNotRunningError` when a sandbox "is not running anymore", `SandboxUnreachableError` when it cannot be reached, and `ServiceBusyError` for an HTTP 503 after which nothing has changed and the call can be retried (E2B SDK error reference). - **Google Cloud:** a Cloud Run job retries a failed task 3 times by default (Cloud Run maximum retries documentation), so check how many attempts a task needed before you call a test flaky. - **Modal:** exit codes "are provided to help diagnose conditions such as success, manual termination, or out-of-memory", and a terminated Sandbox reports 137 (Modal Sandboxes guide). ## Step 3: How do I see what happened in a flaky run? See what happened by recording a trace on the first retry and opening it. Playwright's configuration: ```ts // playwright.config.ts import { defineConfig } from '@playwright/test'; export default defineConfig({ retries: process.env.CI ? 2 : 0, use: { trace: 'on-first-retry' }, }); ``` The trace lets you "Inspect the log, source and network, errors, and console during each step of the test" ([Playwright trace viewer](https://playwright.dev/docs/trace-viewer-intro), read 2026-11-26); open it from the HTML report with `npx playwright show-report`, or directly with `npx playwright show-trace` and the file's path. Playwright advises against tracing every test: "We don't recommend setting this to `on` so that traces are run on every test as it's very performance heavy" ([Playwright best practices](https://playwright.dev/docs/best-practices), read 2026-11-26). In Python, `pytest --tracing retain-on-failure` keeps traces only for failed tests. ## Step 4: How do I remove the usual causes? Remove the usual causes in this order: timing, shared state, load, then outside dependencies. Table: Common causes of flaky browser tests and their fixes | Cause | Symptom | Fix | |---|---|---| | Manual waits and instant checks | Fails on a slow run, passes on a fast one | Web-first assertions: `await expect(locator).toBeVisible()`, never `expect(await locator.isVisible()).toBe(true)` | | Fixed sleeps | Fails under load | Remove `waitForTimeout`; wait for a state with `expect` or `expect.poll` | | Shared state between tests | Fails only after a certain other test | A new context per test, and per-worker test data using `TEST_PARALLEL_INDEX` | | Too many browsers per machine | Timeouts that grow with `--workers` | Fewer workers, or shard across machines | | Third-party services | Fails when an outside site is slow or changes | Mock it with `page.route` and fulfil the response | | Brittle selectors | Fails after markup changes | `getByRole` and other user-facing locators | The sources for each fix: - **Waiting.** Web-first assertions "will wait until the expected condition is met", while with `isVisible()` "the test won't wait a single second" (Playwright best practices, read 2026-11-26). The default assertion timeout is 5 seconds, and "using non-retrying assertions can lead to a flaky test" ([Playwright assertions](https://playwright.dev/docs/test-assertions), read 2026-11-26). - **Isolation.** "Each test should be completely isolated from another test and should run independently" (Playwright best practices, read 2026-11-26). - **Outside services.** "Only test what you control", using "the Playwright Network API" to "guarantee the response needed" (Playwright best practices, read 2026-11-26). - **Missing awaits.** Playwright recommends the `@typescript-eslint/no-floating-promises` rule "to make sure there are no missing awaits". ## How do I fix flaky waits in Selenium? Fix them with explicit waits for a condition. Selenium's docs explain the cause: "The processes often end up in a race condition where sometimes the browser gets into the right state first", and a sleep "can fail when it doesn't sleep long enough" ([Selenium waits](https://www.selenium.dev/documentation/webdriver/waits/), read 2026-11-26). The implicit wait defaults to 0, and the docs warn: "Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times." The docs' explicit wait in Python: ```python from selenium.webdriver.support.wait import WebDriverWait wait = WebDriverWait(driver, timeout=2) wait.until(lambda _ : revealed.is_displayed()) ``` ## When are retries the right answer? Retries are the right answer for failures you have proved come from the environment, not from the test. Playwright's retries are off by default; `retries: 2` or `--retries=2` turns them on, and a retried pass is reported as flaky rather than passed (Playwright retries, read 2026-11-26). Keep that report visible, and treat every test that appears in it as a bug to fix with the table above. ## What we read for this article - Promigence quickstart, [https://www.promigence.ai/docs/quickstart](https://www.promigence.ai/docs/quickstart), read 2026-11-26 - Promigence FAQ, [https://www.promigence.ai/faq](https://www.promigence.ai/faq), read 2026-11-26 - Promigence errors page, [https://www.promigence.ai/docs/errors](https://www.promigence.ai/docs/errors), read 2026-11-26 - Promigence security page, [https://www.promigence.ai/security](https://www.promigence.ai/security), read 2026-11-26 - [Amazon Bedrock AgentCore sessions documentation](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-sessions.html), read 2026-11-26 - [Daytona process documentation](https://www.daytona.io/docs/en/process-code-execution) and [Daytona sandboxes documentation](https://www.daytona.io/docs/en/sandboxes), read 2026-11-26 - [E2B SDK error reference](https://docs.e2b.dev/sdk-reference/js-sdk/v2.64.0/errors), read 2026-11-26 - [Cloud Run maximum retries documentation](https://docs.cloud.google.com/run/docs/configuring/max-retries), read 2026-11-26 - [Modal Sandboxes guide](https://modal.com/docs/guide/sandbox), read 2026-11-26 - [Playwright retries](https://playwright.dev/docs/test-retries), read 2026-11-26 - [Playwright command line](https://playwright.dev/docs/test-cli), read 2026-11-26 - [Playwright CI](https://playwright.dev/docs/ci), read 2026-11-26 - [Playwright trace viewer](https://playwright.dev/docs/trace-viewer-intro), read 2026-11-26 - [Playwright best practices](https://playwright.dev/docs/best-practices), read 2026-11-26 - [Playwright assertions](https://playwright.dev/docs/test-assertions), read 2026-11-26 - [Selenium waits](https://www.selenium.dev/documentation/webdriver/waits/), read 2026-11-26 ## FAQ ### What is a flaky test? A flaky test passes and fails on the same code. Playwright Test labels a test flaky when it failed on the first run but passed when retried. ### Should I just turn on retries? Retries keep a pipeline moving, but they hide the cause. Turn them on with tracing on the first retry, read the traces, and fix the tests that keep showing up as flaky. --fail-on-flaky-tests stops flaky passes from counting as green. ### How do I reproduce a flaky Playwright test locally? Run it many times in a row with npx playwright test --repeat-each=20, optionally with --workers set to match the CI machine, and record a trace with --trace on. ### Why are my browser tests flaky only on CI? CI machines often have fewer cores, so the same number of parallel browsers renders pages later than on a laptop and timing assumptions break. Lower the workers, or check whether the failures come from the environment rather than the tests. ### How do I avoid flaky waits in Selenium? Replace sleeps with explicit waits for a specific condition, keep the implicit wait at its default of 0, and never mix implicit and explicit waits. --- # Playwright CLI: every command and the test options that matter URL: https://www.agentsandbox.host/p/playwright-cli-commands/ Author: AgentSandbox.host editors Published: 2026-11-26 Updated: 2026-11-26 The Playwright CLI is the npx playwright command. Its main commands are test, show-report, show-trace, codegen (record a test), install and install-deps (browsers and system packages) and merge-reports; npx playwright test takes options for filters, workers, shards, retries, traces and debugging. The Playwright CLI is the `npx playwright` command that comes with the `@playwright/test` package (in Python, the `playwright` command). It runs tests, records new ones, installs browsers and opens reports and traces. Every description below is quoted from Playwright's command line reference, version 1.65 ([Playwright command line](https://playwright.dev/docs/test-cli), read 2026-11-26), unless another source is named. ## Which commands does the Playwright CLI have? The Playwright CLI's commands for testing work are below. The reference page documents the first nine; the last three appear in `npx playwright --help`, which we ran with version 1.65.1 on 26 November 2026. Table: Playwright CLI commands | Command | What it does | |---|---| | `npx playwright test` | Runs the tests | | `npx playwright show-report` | Serves the HTML report; default port 9323 | | `npx playwright show-trace ` | Opens a trace in the trace viewer | | `npx playwright codegen ` | Opens a browser and writes test code as you click | | `npx playwright install [browser...]` | Downloads browser builds | | `npx playwright install-deps [browser...]` | Installs the operating system packages the browsers need | | `npx playwright uninstall` | Removes browsers | | `npx playwright merge-reports ` | Merges blob reports from shards into one report | | `npx playwright clear-cache` | "Clear all Playwright caches" | | `npx playwright open [url]` | Opens a page in a browser (help: "open page in browser specified via -b, --browser") | | `npx playwright screenshot ` | Captures a screenshot of a page | | `npx playwright pdf ` | Saves a page as PDF | Two more commands belong to agent work rather than tests: since release 1.62, "Playwright now bundles the Playwright MCP server and playwright-cli, runnable via npx playwright mcp and npx playwright cli" ([Playwright release notes](https://playwright.dev/docs/release-notes), read 2026-11-26). ## Which npx playwright test options are used most? These options cover most daily runs: Table: Common npx playwright test options | Option | What it does | Default | |---|---|---| | `--headed` | "Run tests in headed browsers" | headless | | `--ui` | "Run tests in interactive UI mode" | off | | `--debug` | "Run tests with Playwright Inspector" | off | | `--project ` | Only these projects; `*` wildcards allowed | all projects | | `-g, --grep ` | Only tests matching the expression | `.*` | | `-G, --grep-invert ` | Only tests not matching it | none | | `--list` | "Collect all the tests and report them, but do not run" | off | | `--last-failed` | "Only re-run the failures" | off | | `--only-changed [ref]` | Only test files changed between HEAD and the ref (git) | uncommitted changes | | `-j, --workers ` | Worker count, or a percentage of logical CPU cores | 50% | | `--shard ` | Run one shard, 1-based, such as `3/5` | no sharding | | `--retries ` | "Maximum retry count for flaky tests" | no retries | | `--repeat-each ` | "Run each test `N` times" | 1 | | `--trace ` | `on`, `off`, `on-first-retry`, `on-all-retries` and retain modes | from config | | `--timeout ` | Per-test timeout, 0 for unlimited | 30 seconds | | `--global-timeout ` | "Maximum time this test suite can run" | unlimited | | `-x`, `--max-failures ` | Stop after the first failure, or after N | off | | `--reporter ` | `dot`, `line`, `list`, `failures` and others | `list` locally, `dot` on CI | | `--fail-on-flaky-tests` | "Fail if any test is flagged as flaky" | false | | `--forbid-only` | "Fail if `test.only` is called" | false | | `-u, --update-snapshots [mode]` | Update snapshots: `all`, `changed`, `missing`, `none` | default | | `--shuffle [seed]` | "Schedule tests in a random order" | off | Positional arguments filter by file: each is a regular expression matched against the test file's path, so `npx playwright test login` runs every file with "login" in its path. A file and line, `npx playwright test example.spec.ts:10`, runs one test ([Playwright running tests](https://playwright.dev/docs/running-tests), read 2026-11-26). ## How do I record a test with codegen? Run `npx playwright codegen` with the address of your app; a browser opens and the inspector writes code as you click. Useful options from [Playwright codegen](https://playwright.dev/docs/codegen) (read 2026-11-26): ``` npx playwright codegen demo.playwright.dev/todomvc npx playwright codegen --viewport-size="800,600" playwright.dev npx playwright codegen --device="iPhone 13" playwright.dev npx playwright codegen --color-scheme=dark playwright.dev ``` `--save-storage=auth.json` saves cookies and storage after you sign in by hand, and `--load-storage=auth.json` starts the next session signed in. `--target` picks the output language, such as `python`, and `-o` writes to a file. ## How do I install browsers from the CLI? Install browsers with `npx playwright install`, choosing what you need ([Playwright browsers](https://playwright.dev/docs/browsers), read 2026-11-26): ``` npx playwright install # the default browsers npx playwright install --with-deps chromium # Chromium and its system packages npx playwright install --with-deps --only-shell # headless shell only npx playwright install --with-deps --no-shell # full Chromium, no headless shell ``` Playwright "ships a regular Chromium build for headed operations and a separate chromium headless shell for headless mode", so `--only-shell` saves a download when nothing runs headed. `--dry-run` prints what would be installed, `--list` shows the browsers of every Playwright installation on the machine, and `npx playwright install-deps --dry-run` on Linux "simulates the apt-get install" and exits non-zero if packages are missing (Playwright command line, read 2026-11-26). ## Which environment variables does the CLI read? The CLI reads several environment variables, documented across Playwright's pages: Table: Environment variables for the Playwright CLI | Variable | Effect | Source | |---|---|---| | `PLAYWRIGHT_BROWSERS_PATH` | Where browsers are installed and looked for | [Playwright browsers](https://playwright.dev/docs/browsers) | | `PLAYWRIGHT_SKIP_BROWSER_GC=1` | Keep browser versions no installation uses any more | Playwright browsers | | `PLAYWRIGHT_DOWNLOAD_HOST` | Download browsers from your own mirror | Playwright browsers | | `DEBUG=pw:browser` | Log browser launches | [Playwright CI](https://playwright.dev/docs/ci) | | `PWDEBUG=1` | Run with the Inspector (Python: `PWDEBUG=1 pytest -s`) | [Playwright Python running tests](https://playwright.dev/python/docs/running-tests) | | `PW_TEST_CONNECT_WS_ENDPOINT` | Run tests against a remote browser server | [Playwright Docker](https://playwright.dev/docs/docker) | | `PLAYWRIGHT_JSON_OUTPUT_NAME` | File name for the JSON reporter | [Playwright reporters](https://playwright.dev/docs/test-reporters) | | `PLAYWRIGHT_TRANSFORM_CACHE_DIR` | Where transpiled tests are cached | Playwright command line | All sources in this table were read on 2026-11-26. ## What is the Python version of the CLI? In Python the same commands are run as `playwright` after `pip install playwright`, for example `playwright install --with-deps chromium`, `playwright codegen --target python` and `playwright show-trace trace.zip`. Tests run through pytest instead of `playwright test`; see our [Playwright Python setup guide](https://www.agentsandbox.host/p/playwright-python-tutorial/). ## What we read for this article - [Playwright command line](https://playwright.dev/docs/test-cli), read 2026-11-26 - [Playwright running tests](https://playwright.dev/docs/running-tests), read 2026-11-26 - [Playwright codegen](https://playwright.dev/docs/codegen), read 2026-11-26 - [Playwright browsers](https://playwright.dev/docs/browsers), read 2026-11-26 - [Playwright release notes](https://playwright.dev/docs/release-notes), read 2026-11-26 - [Playwright CI](https://playwright.dev/docs/ci), read 2026-11-26 - [Playwright Docker](https://playwright.dev/docs/docker), read 2026-11-26 - [Playwright reporters](https://playwright.dev/docs/test-reporters), read 2026-11-26 - [Playwright Python running tests](https://playwright.dev/python/docs/running-tests), read 2026-11-26 ## FAQ ### How do I run a single Playwright test from the command line? Pass the file and line, npx playwright test example.spec.ts:10, or a title pattern with -g, npx playwright test -g "add a todo item". ### How do I list Playwright tests without running them? Run npx playwright test --list. It collects all tests and reports them without running any. ### What is the default Playwright test timeout? 30 seconds per test. Change it with --timeout in milliseconds, or the timeout option in the config. --global-timeout caps the whole run and is unlimited by default. ### How do I install only Chromium for Playwright? Run npx playwright install --with-deps chromium. For headless-only runs, npx playwright install --with-deps --only-shell installs the smaller headless shell instead of full Chromium. ### Is there a Playwright CLI for coding agents? Yes. Since release 1.62 the playwright package bundles playwright-cli and the Playwright MCP server, run as npx playwright cli and npx playwright mcp. --- # Playwright async in Python: when to use it and how URL: https://www.agentsandbox.host/p/playwright-python-async/ Author: AgentSandbox.host editors Published: 2026-11-26 Updated: 2026-11-26 Use Playwright's async API in Python when your code already runs on asyncio. Import async_playwright from playwright.async_api, await every call, and start it with asyncio.run. For pytest, install pytest-playwright-asyncio and mark tests with the session loop scope. Playwright for Python ships two APIs with the same methods: a synchronous one in `playwright.sync_api` and an asynchronous one in `playwright.async_api`. Playwright's own guidance is short: "If your modern project uses asyncio, you should use async API" ([Playwright Python library](https://playwright.dev/python/docs/library), read 2026-11-26). ## When should I use the async API instead of the sync API? Use the async API when your program already runs an asyncio event loop, or when one process must drive several pages at once. Use the sync API for plain scripts and ordinary pytest suites. Table: Choosing between Playwright's sync and async APIs in Python | Situation | API | Why | |---|---|---| | A pytest suite, one page per test | Sync | Simplest code; the plugin gives each test its own page | | A script that visits pages one by one | Sync | No event loop to manage | | An asyncio web service or worker | Async | The sync API refuses to start inside a running event loop | | Many pages driven from one process | Async | Waits overlap, so total time follows the slowest page rather than the sum | | Code split across threads | Either, one instance per thread | "Playwright's API is not thread-safe" (Playwright Python library, read 2026-11-26) | ## How do I write a first async Playwright script? Wrap the work in an `async` function, enter `async_playwright()` with `async with`, await every call, and start it with `asyncio.run`. This is the shape of Playwright's own async example ([Playwright Python BrowserType API](https://playwright.dev/python/docs/api/class-browsertype), read 2026-11-26): ```python import asyncio from playwright.async_api import async_playwright, Playwright async def run(playwright: Playwright): chromium = playwright.chromium browser = await chromium.launch() page = await browser.new_page() await page.goto("https://example.com") # other actions... await browser.close() async def main(): async with async_playwright() as playwright: await run(playwright) asyncio.run(main()) ``` Install it the same way as the sync API: `pip install playwright`, then `playwright install` to download the browsers (Playwright Python library, read 2026-11-26). ## How do I run several pages at the same time? Run several pages at once by creating one browser, one context per job, and gathering the jobs. `asyncio.gather` will "Run awaitable objects in the aws sequence concurrently" ([Python asyncio tasks](https://docs.python.org/3/library/asyncio-task.html), read 2026-11-26), and a semaphore caps how many run together ([Python asyncio synchronization primitives](https://docs.python.org/3/library/asyncio-sync.html), read 2026-11-26). ```python import asyncio from playwright.async_api import async_playwright URLS = [ "https://example.com", "https://playwright.dev", "https://www.python.org", ] async def title_of(browser, url, limit): async with limit: context = await browser.new_context() try: page = await context.new_page() await page.goto(url) return url, await page.title() finally: await context.close() async def main(): limit = asyncio.Semaphore(4) async with async_playwright() as p: browser = await p.chromium.launch() results = await asyncio.gather(*(title_of(browser, u, limit) for u in URLS)) await browser.close() for url, title in results: print(url, title) asyncio.run(main()) ``` We ran this script with playwright 1.65.2 and Chromium on 26 November 2026; it printed the three page titles. Each job gets its own context, so cookies and storage never mix between jobs. Playwright describes contexts as "fast and cheap to create" and "completely isolated, even when running in a single browser" ([Playwright browser contexts](https://playwright.dev/docs/browser-contexts), read 2026-11-26). The semaphore matters: every open page uses memory and CPU, and an unbounded `gather` over a long list opens them all at once. ## How do I write async tests with pytest? Write async tests with the separate pytest-playwright-asyncio plugin. Playwright's instructions: "To use async fixtures, install pytest-playwright-asyncio", and "Ensure you are using pytest-asyncio>=0.26.0 and set asyncio_default_test_loop_scope = session in your configuration" ([Playwright Python test runners](https://playwright.dev/python/docs/test-runners), read 2026-11-26). 1. Install the plugin: ``` pip install pytest-playwright-asyncio playwright install ``` 2. Set the loop scope in `pyproject.toml`: ```toml [tool.pytest.ini_options] asyncio_default_test_loop_scope = "session" ``` 3. Write the test with the session loop scope, as in Playwright's example (Playwright Python test runners, read 2026-11-26): ```python import pytest from playwright.async_api import Page @pytest.mark.asyncio(loop_scope="session") async def test_foo(page: Page): await page.goto("https://github.com") # ... ``` The session loop scope matters because the browser fixture lives for the whole session. A test that ran on its own event loop could not use a browser created on another loop. Version 0.10.0 of pytest-playwright-asyncio, current on PyPI when we checked, requires Python 3.10 or newer and pytest 8.2.0 or newer ([PyPI: pytest-playwright-asyncio](https://pypi.org/project/pytest-playwright-asyncio/), read 2026-11-26). ## What goes wrong most often with async Playwright? Four mistakes cause most async Playwright errors: 1. **A missing `await`.** The call returns a coroutine and nothing happens. Assertions then pass or fail for the wrong reason. 2. **Calling the sync API inside an event loop.** We ran `sync_playwright()` inside `asyncio.run` with playwright 1.65.2 on 26 November 2026, and it stopped with "It looks like you are using Playwright Sync API inside the asyncio loop. Please use the Async API instead." Inside a running loop, such as a notebook or an async web framework, use `playwright.async_api`. 3. **Changing the Windows event loop.** Playwright "requires `ProactorEventLoop` of `asyncio`" on Windows, because the selector loop "does not supports async subprocesses" (Playwright Python library, read 2026-11-26). 4. **Sharing one instance across threads.** Create "a playwright instance per thread" if you must use threads (Playwright Python library, read 2026-11-26). New to Playwright in Python? Start with our [Playwright Python setup guide](https://www.agentsandbox.host/p/playwright-python-tutorial/). ## What we read for this article - [Playwright Python library](https://playwright.dev/python/docs/library), read 2026-11-26 - [Playwright Python BrowserType API](https://playwright.dev/python/docs/api/class-browsertype), read 2026-11-26 - [Playwright Python test runners](https://playwright.dev/python/docs/test-runners), read 2026-11-26 - [Playwright browser contexts](https://playwright.dev/docs/browser-contexts), read 2026-11-26 - [Python asyncio tasks](https://docs.python.org/3/library/asyncio-task.html), read 2026-11-26 - [Python asyncio synchronization primitives](https://docs.python.org/3/library/asyncio-sync.html), read 2026-11-26 - [PyPI: pytest-playwright-asyncio](https://pypi.org/project/pytest-playwright-asyncio/), read 2026-11-26 ## FAQ ### Is Playwright's async API faster than the sync API in Python? Not for one page. Both drive the same browser. Async helps when one process must drive several pages or browsers at the same time, because the waits overlap instead of running one after another. ### Can I use Playwright from several threads? Playwright's API is not thread-safe. Its documentation says to create a Playwright instance per thread if you use threads. With asyncio you can run many pages concurrently in a single thread instead. ### Why does Playwright fail with NotImplementedError on Windows? Playwright needs asyncio's ProactorEventLoop on Windows, because the SelectorEventLoop does not support async subprocesses. Do not switch the event loop policy to the selector loop in code that starts Playwright. ### How do I write async Playwright tests with pytest? Install pytest-playwright-asyncio, use pytest-asyncio 0.26.0 or newer, set asyncio_default_test_loop_scope = session in your pytest configuration, and decorate each test with @pytest.mark.asyncio(loop_scope="session"). --- # Playwright with Python: install it and write your first test URL: https://www.agentsandbox.host/p/playwright-python-tutorial/ Author: AgentSandbox.host editors Published: 2026-11-26 Updated: 2026-11-26 To start with Playwright in Python, install the pytest plugin with pip install pytest-playwright, download the browsers with playwright install, write a test function that takes the page fixture, and run pytest. Tests run headless in Chromium by default; --headed and --browser change that. Playwright for Python is the Python version of the Playwright browser automation library, and pytest-playwright is its official plugin for pytest. This guide installs both, writes one test, runs it in three browsers and shows where the output goes. ## What do I need before installing Playwright for Python? You need a supported Python and a supported operating system. The playwright package on PyPI, version 1.65.2 on the day we checked, declares `Requires-Python >=3.10` ([PyPI: playwright](https://pypi.org/project/playwright/), read 2026-11-26). Playwright's Python introduction lists these systems ([Playwright Python installation](https://playwright.dev/python/docs/intro), read 2026-11-26): - Windows 11+, Windows Server 2019+ or Windows Subsystem for Linux (WSL) - macOS 14 (Sonoma) or later - Debian 12 / 13, Ubuntu 22.04 / 24.04 / 26.04 (x86-64 or arm64) The same page still says "Python 3.8 or higher". The package metadata is newer, so treat 3.10 as the floor. ## How do I install Playwright and pytest-playwright? Install the plugin, which pulls in Playwright, then download the browsers. 1. Create and activate a virtual environment: ``` python -m venv .venv source .venv/bin/activate ``` 2. Install the plugin with your package manager. The official commands are `pip install pytest-playwright`, `poetry add pytest-playwright` or `uv add pytest-playwright` (Playwright Python installation, read 2026-11-26). ``` pip install pytest-playwright ``` 3. Download the browser builds: ``` playwright install ``` Playwright says this step installs "browser binaries for Chromium, Firefox and WebKit" ([Playwright Python library](https://playwright.dev/python/docs/library), read 2026-11-26). On a fresh Linux machine, `playwright install --with-deps` also installs the system packages the browsers need ([Playwright browsers](https://playwright.dev/docs/browsers), read 2026-11-26). ## How do I write my first Playwright test in Python? Write a function whose name starts with `test_` and that takes the `page` fixture. This is Playwright's own first example, saved as `test_example.py` (Playwright Python installation, read 2026-11-26): ```python import re from playwright.sync_api import Page, expect def test_has_title(page: Page): page.goto("https://playwright.dev/") expect(page).to_have_title(re.compile("Playwright")) def test_get_started_link(page: Page): page.goto("https://playwright.dev/") page.get_by_role("link", name="Get started").click() expect(page.get_by_role("heading", name="Installation")).to_be_visible() ``` We ran this file with pytest-playwright 0.10.0, playwright 1.65.2 and Chromium on 26 November 2026, and both tests passed. Three things in it do most of the work: 1. **The `page` fixture.** The plugin hands each test a "New browser page for a test", inside a "New browser context for a test" ([Playwright Python test runners](https://playwright.dev/python/docs/test-runners), read 2026-11-26). No cookies or storage carry over between tests. 2. **Locators by role.** `get_by_role("link", name="Get started")` finds the element the way a user would, which survives most markup changes. 3. **`expect`.** Playwright's assertions wait and retry until the condition holds or the timeout passes, so the test needs no `sleep`. ## How do I run the test? Run `pytest` in the project folder. Playwright notes that "By default tests will be run on chromium" and that "Tests are run in headless mode meaning no browser UI will open up when running the tests" (Playwright Python installation, read 2026-11-26). The commands you will use most, from [Playwright Python: running tests](https://playwright.dev/python/docs/running-tests) (read 2026-11-26): Table: Common pytest commands for Playwright | Task | Command | |---|---| | Run every test | `pytest` | | Show the browser | `pytest --headed` | | Run in WebKit | `pytest --browser webkit` | | Run in two browsers | `pytest --browser webkit --browser firefox` | | Run one file | `pytest test_login.py` | | Run tests whose name matches | `pytest -k test_add_a_todo_item` | | Step through with the Inspector | `PWDEBUG=1 pytest -s` | ## Which pytest-playwright options should I know? These plugin options cover most day-to-day needs. Each description is the plugin's own (Playwright Python test runners, read 2026-11-26): Table: pytest-playwright command line options and their defaults | Option | What it does | Default | |---|---|---| | `--headed` | Run tests in headed mode | headless | | `--browser` | `chromium`, `firefox` or `webkit`; may be repeated | `chromium` | | `--browser-channel` | Browser channel to use, such as `chrome` | not set | | `--slowmo` | Slow each operation by this many milliseconds | not set | | `--device` | Device to emulate | not set | | `--output` | Directory for artifacts produced by tests | `test-results` | | `--tracing` | `on`, `off` or `retain-on-failure` | `off` | | `--video` | `on`, `off` or `retain-on-failure` | `off` | | `--screenshot` | `on`, `off` or `only-on-failure` | `off` | A useful default for a shared test run is `--tracing retain-on-failure`: a trace is kept only for the tests that failed, and you open it with `playwright show-trace` followed by the trace file's path. ## Which fixtures does the plugin provide? The plugin provides fixtures at two scopes. Per test (function scope): `context`, `page` and `new_context`, the last for tests that need several users at once. Per session: `playwright`, `browser_type`, `browser`, `browser_name`, `browser_channel` and the booleans `is_chromium`, `is_webkit` and `is_firefox` (Playwright Python test runners, read 2026-11-26). The split matters for speed and isolation: the browser starts once per session, while every test gets a new context, which is cheap to create and shares nothing with the previous test. ## How do I keep Playwright up to date? Upgrade both packages together, then download the matching browsers. The official pip command is `pip install pytest-playwright playwright -U` (Playwright Python installation, read 2026-11-26), followed by: ``` playwright install ``` Each Playwright release expects specific browser builds: "Each version of Playwright needs specific versions of browser binaries to operate" (Playwright browsers, read 2026-11-26). Skip the second step and the upgraded library looks for browser builds that are not on the machine. If your code uses `asyncio`, read our guide to the [Playwright async API in Python](https://www.agentsandbox.host/p/playwright-python-async/) next. To spread the suite over several processes, see [running browser tests in parallel](https://www.agentsandbox.host/p/run-browser-tests-in-parallel/). ## What we read for this article - [Playwright Python installation](https://playwright.dev/python/docs/intro), read 2026-11-26 - [Playwright Python library](https://playwright.dev/python/docs/library), read 2026-11-26 - [Playwright Python test runners](https://playwright.dev/python/docs/test-runners), read 2026-11-26 - [Playwright Python: running tests](https://playwright.dev/python/docs/running-tests), read 2026-11-26 - [Playwright browsers](https://playwright.dev/docs/browsers), read 2026-11-26 - [PyPI: playwright](https://pypi.org/project/playwright/), read 2026-11-26 ## FAQ ### What Python version does Playwright need? The current playwright package on PyPI (1.65.2 when we checked on 26 November 2026) declares Python 3.10 or newer. The getting-started page still says 3.8 or higher, so go by the package's own requirement. ### Do I need pytest to use Playwright in Python? No. The playwright package works as a plain library with a sync or async API. The pytest plugin, pytest-playwright, is the recommended way to write end-to-end tests because it gives each test a fresh page and context. ### Why does my Playwright test not open a browser window? Tests run headless by default, so no window opens. Run pytest --headed to see the browser. ### How do I run Playwright tests in Firefox or WebKit from Python? Pass --browser firefox or --browser webkit to pytest. The option can be given more than once to run the same tests in several browsers. ### How do I update Playwright in a Python project? Run pip install pytest-playwright playwright -U, then playwright install again so the browser builds match the new version. --- # Playwright testing with Node.js: install, first test, config URL: https://www.agentsandbox.host/p/playwright-testing-with-node/ Author: AgentSandbox.host editors Published: 2026-11-26 Updated: 2026-11-26 To start Playwright testing in Node.js, run npm init playwright@latest, which adds @playwright/test, a playwright.config.ts and an example test, then run npx playwright test. Tests use the page fixture, role-based locators and retrying assertions; npx playwright show-report opens the results. Playwright Test is Playwright's own test runner for Node.js, published as the npm package `@playwright/test`. It bundles the runner, the browser fixtures and web-first assertions, so a new project needs nothing else. The current release when we checked was 1.65.1 ([npm: @playwright/test](https://www.npmjs.com/package/@playwright/test), read 2026-11-26). ## What do I need before I start? You need a supported Node.js and operating system. Playwright's installation page lists "Node.js: latest 22.x, 24.x or 26.x", and Windows 11+, Windows Server 2019+ or WSL, macOS 14 (Sonoma) or later, and Debian 12 / 13 or Ubuntu 22.04 / 24.04 / 26.04 on x86-64 or arm64 ([Playwright installation](https://playwright.dev/docs/intro), read 2026-11-26). ## How do I install Playwright Test? Install Playwright Test with its project generator, then let it download the browsers. 1. In your project folder, run the generator. The npm form is below; `yarn create playwright` and `pnpm create playwright` do the same (Playwright installation, read 2026-11-26). ``` npm init playwright@latest ``` 2. Answer its questions: TypeScript or JavaScript, the name of the tests folder, whether to add a CI workflow, and whether to install the browsers now. Re-running it later "does not overwrite existing tests". 3. Check what it created: `playwright.config.ts`, and a tests folder holding `example.spec.ts`, a minimal example test. To add Playwright to an existing project by hand instead: ``` npm install -D @playwright/test npx playwright install --with-deps ``` The second command downloads the browser builds and, on Linux, the system packages they need ([Playwright command line](https://playwright.dev/docs/test-cli), read 2026-11-26). ## How do I write my first test? Write a test with the `test` function, take the `page` fixture, and assert with `expect`. This is Playwright's first example, saved as `tests/example.spec.ts` ([Playwright writing tests](https://playwright.dev/docs/writing-tests), read 2026-11-26): ```ts import { test, expect } from '@playwright/test'; test('has title', async ({ page }) => { await page.goto('https://playwright.dev/'); // Expect a title "to contain" a substring. await expect(page).toHaveTitle(/Playwright/); }); test('get started link', async ({ page }) => { await page.goto('https://playwright.dev/'); // Click the get started link. await page.getByRole('link', { name: 'Get started' }).click(); // Expects page to have a heading with the name of Installation. await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible(); }); ``` We ran this file with @playwright/test 1.65.1 and Chromium on 26 November 2026, and both tests passed. What makes it reliable: - **Isolation.** "Pages are isolated between tests due to the Browser Context, which is equivalent to a brand new browser profile" (Playwright writing tests, read 2026-11-26). - **Auto-waiting.** Before a click, Playwright checks that the element is visible, stable, receives events and is enabled ([Playwright actionability](https://playwright.dev/docs/actionability), read 2026-11-26). - **Retrying assertions.** `toHaveTitle` and `toBeVisible` keep checking until they pass; "By default, the timeout for assertions is set to 5 seconds" ([Playwright assertions](https://playwright.dev/docs/test-assertions), read 2026-11-26). The actions you will use most are `click`, `fill`, `check`, `uncheck`, `hover`, `focus`, `press`, `setInputFiles` and `selectOption`. The assertions you will use most include `toBeVisible`, `toHaveText`, `toContainText`, `toHaveValue`, `toHaveURL` and `toHaveCount` (Playwright writing tests, read 2026-11-26). ## What should playwright.config.ts contain? The config file sets where tests live, how many run at once, retries, reporters and which browsers to use. A starting config with the options from Playwright's configuration guide ([Playwright test configuration](https://playwright.dev/docs/test-configuration), read 2026-11-26): ```ts import { defineConfig, devices } from '@playwright/test'; export default defineConfig({ testDir: 'tests', fullyParallel: true, forbidOnly: !!process.env.CI, retries: process.env.CI ? 2 : 0, reporter: 'html', use: { baseURL: process.env.BASE_URL, trace: 'on-first-retry', }, projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, { name: 'firefox', use: { ...devices['Desktop Firefox'] } }, { name: 'webkit', use: { ...devices['Desktop Safari'] } }, ], }); ``` Two defaults are worth knowing: workers "Defaults to half of the number of logical CPU cores", and each test has a timeout that "Defaults to 30 seconds" ([Playwright TestConfig](https://playwright.dev/docs/api/class-testconfig), read 2026-11-26). If your tests need your app running, add a `webServer` block with the `command` that starts it and the `url` to wait for; Playwright waits up to 60000 ms for it by default. ## How do I run the tests? Run `npx playwright test`. The commands for day-to-day work, from [Playwright running tests](https://playwright.dev/docs/running-tests) (read 2026-11-26): Table: Everyday Playwright Test commands | Task | Command | |---|---| | Run every test | `npx playwright test` | | Show the browsers | `npx playwright test --headed` | | One browser project | `npx playwright test --project webkit` | | One file | `npx playwright test landing-page.spec.ts` | | Tests whose title matches | `npx playwright test -g "add a todo item"` | | Only the tests that failed last time | `npx playwright test --last-failed` | | Interactive UI mode | `npx playwright test --ui` | | Step through with the Inspector | `npx playwright test --debug` | | Open the HTML report | `npx playwright show-report` | Our [Playwright CLI reference](https://www.agentsandbox.host/p/playwright-cli-commands/) lists every option, and [running browser tests in parallel](https://www.agentsandbox.host/p/run-browser-tests-in-parallel/) covers workers and sharding. ## How do I update Playwright? Update the package and the browsers together. Playwright's commands are `npm install -D @playwright/test@latest` and then `npx playwright install --with-deps`; `npx playwright --version` shows which version you have (Playwright installation, read 2026-11-26). ## What we read for this article - [Playwright installation](https://playwright.dev/docs/intro), read 2026-11-26 - [Playwright writing tests](https://playwright.dev/docs/writing-tests), read 2026-11-26 - [Playwright running tests](https://playwright.dev/docs/running-tests), read 2026-11-26 - [Playwright test configuration](https://playwright.dev/docs/test-configuration), read 2026-11-26 - [Playwright TestConfig](https://playwright.dev/docs/api/class-testconfig), read 2026-11-26 - [Playwright actionability](https://playwright.dev/docs/actionability), read 2026-11-26 - [Playwright assertions](https://playwright.dev/docs/test-assertions), read 2026-11-26 - [Playwright command line](https://playwright.dev/docs/test-cli), read 2026-11-26 - [Playwright Library](https://playwright.dev/docs/library), read 2026-11-26 - [npm: @playwright/test](https://www.npmjs.com/package/@playwright/test), read 2026-11-26 ## FAQ ### Which Node.js versions does Playwright support? Playwright's installation page lists the latest 22.x, 24.x and 26.x releases. The @playwright/test package itself (1.65.1 when we checked) declares Node.js 20 or newer as its engine. ### What is the difference between playwright and @playwright/test? The playwright package is Playwright Library, which gives the APIs to launch and drive browsers. The @playwright/test package is Playwright Test, which adds a managed test runner with fixtures and assertions. Install the library for scripts and @playwright/test for tests. ### How many tests does Playwright run at once? By default Playwright Test uses worker processes up to half the number of logical CPU cores. Set workers in the config or pass --workers to change it. ### How do I see the browser while a test runs? Run npx playwright test --headed, or npx playwright test --ui for the interactive UI mode, or npx playwright test --debug to step through with the Inspector. --- # Playwright vs Selenium: a sourced comparison table URL: https://www.agentsandbox.host/p/playwright-vs-selenium/ Author: AgentSandbox.host editors Published: 2026-11-26 Updated: 2026-11-26 Data as of: 2026-11-26 Data files: https://www.agentsandbox.host/data/playwright-vs-selenium.csv (CSV), https://www.agentsandbox.host/data/playwright-vs-selenium.json (JSON) Playwright and Selenium are both Apache-2.0 browser automation projects. Playwright gives one API over pinned Chromium, Firefox and WebKit builds with auto-waiting and its own runner; Selenium implements W3C WebDriver in six languages and scales out with Selenium Grid. Table: Playwright and Selenium compared, from each project's own documentation | Tool | License | Latest release checked | Official languages | Browsers | How it drives the browser | Waiting for the page | Test runner | Parallel on one machine | Across machines | Browser and driver downloads | Official Docker image | Source | Checked | |---|---|---|---|---|---|---|---|---|---|---|---|---|---| | Playwright | Apache-2.0 | 1.65.1 (Node.js), 1.65.2 (Python) | JavaScript and TypeScript, Python, Java, .NET | Chromium, Firefox and WebKit builds pinned to each release; Chrome and Edge through channels | Its own library with one API for all three engines | Actions wait for actionability checks; web-first assertions retry for 5 seconds by default | Playwright Test for Node.js; the pytest plugin for Python; JUnit, TestNG, MSTest, NUnit or xUnit elsewhere | Worker processes, by default half the logical CPU cores, each with its own browser | Sharding with --shard=x/y, then merge-reports to combine the results | npx playwright install downloads the browser builds a release needs | mcr.microsoft.com/playwright, tags such as v1.65.1-noble | [playwright.dev/docs/intro](https://playwright.dev/docs/intro) | 2026-11-26 | | Selenium | Apache-2.0 | 4.54.0 | Java, Python, C#, Ruby, JavaScript, Kotlin | Chrome, Edge, Firefox, Safari and Internet Explorer through their drivers | An implementation of the W3C WebDriver specification | Implicit wait defaults to 0; explicit waits poll for a condition you write | Your language's runner; the docs show JUnit, pytest, MSTest, RSpec and Mocha | Through your test framework, for example pytest-xdist | Selenium Grid routes sessions to Nodes on many machines | Selenium Manager, a Rust command-line tool the bindings use by default | selenium/standalone-chrome, selenium/hub and selenium/node-chrome, tags such as 4.54.0-20261124 | [www.selenium.dev/documentation](https://www.selenium.dev/documentation/) | 2026-11-26 | ## Method Every cell was read on the checked date from each project's own documentation, release notes or package registry, listed under the table; each row links the project's main page. ## How do Playwright and Selenium differ in one paragraph? Playwright and Selenium differ mainly in scope. Playwright is a library plus a test runner that downloads its own browser builds and waits for the page automatically ([Playwright repository](https://github.com/microsoft/playwright), read 2026-11-26). Selenium is "an umbrella project for a range of tools and libraries that enable and support the automation of web browsers", built on "the W3C WebDriver specification", with Selenium Grid for running browsers on remote machines ([Selenium documentation](https://www.selenium.dev/documentation/), read 2026-11-26). ## How does each one wait for the page? Playwright waits before acting and while asserting; Selenium waits only where you tell it to. - **Playwright.** "Playwright performs a range of actionability checks on the elements before making actions", and web-first assertions retry; "By default, the timeout for assertions is set to 5 seconds" ([Playwright actionability](https://playwright.dev/docs/actionability), [Playwright assertions](https://playwright.dev/docs/test-assertions), read 2026-11-26). - **Selenium.** The implicit wait's "default value is `0`, which means that if the element is not found, it will immediately return an error." Explicit waits "poll the application for a specific condition", and the docs warn: "Do not mix implicit and explicit waits" ([Selenium waits](https://www.selenium.dev/documentation/webdriver/waits/), read 2026-11-26). ## How does each one run many browsers at once? Both run many browsers at once, by different routes. Table: Scaling out with Playwright and Selenium | Need | Playwright | Selenium | |---|---|---| | Several tests on one machine | Worker processes; the default is half the logical CPU cores ([Playwright TestConfig](https://playwright.dev/docs/api/class-testconfig)) | Your test framework's parallel mode, for example `pytest --numprocesses auto` with pytest-xdist | | Many machines | `npx playwright test --shard=1/4` on each machine, then `npx playwright merge-reports` ([Playwright sharding](https://playwright.dev/docs/test-sharding)) | Selenium Grid: tests send sessions to one address and Nodes on many machines run them ([Selenium Grid](https://www.selenium.dev/documentation/grid/)) | | Mixed browser versions and platforms | One browser build per release, plus Chrome and Edge channels | Grid Nodes with different browsers, versions and systems | Our guides cover [parallel workers and sharding](https://www.agentsandbox.host/p/run-browser-tests-in-parallel/) and [Selenium Grid in Docker](https://www.agentsandbox.host/p/selenium-grid-docker/) step by step. ## How do I choose between them? Choose by the constraints you already have, not by reputation. 1. **Language.** A Ruby or Kotlin team has an official Selenium binding and no official Playwright one. 2. **Browsers.** You need Safari itself: Selenium with its driver. WebKit on Linux in a container: Playwright. 3. **Existing infrastructure.** A working Selenium Grid and a large suite are a reason to stay; a new project with no runner yet gets one with Playwright Test. 4. **Flaky waits.** If most failures are timing, Playwright's auto-waiting removes the class of bug that explicit waits leave to the author. Our guide to [fixing flaky browser tests](https://www.agentsandbox.host/p/fix-flaky-browser-tests/) covers both tools. ## What we read for this page - [Playwright repository](https://github.com/microsoft/playwright), read 2026-11-26 - [Playwright installation](https://playwright.dev/docs/intro), [languages](https://playwright.dev/docs/languages), [browsers](https://playwright.dev/docs/browsers), [release notes](https://playwright.dev/docs/release-notes), read 2026-11-26 - [Playwright actionability](https://playwright.dev/docs/actionability) and [assertions](https://playwright.dev/docs/test-assertions), read 2026-11-26 - [Playwright TestConfig](https://playwright.dev/docs/api/class-testconfig), [parallelism](https://playwright.dev/docs/test-parallel) and [sharding](https://playwright.dev/docs/test-sharding), read 2026-11-26 - [Playwright Docker](https://playwright.dev/docs/docker), read 2026-11-26 - [npm: @playwright/test](https://www.npmjs.com/package/@playwright/test) and [PyPI: playwright](https://pypi.org/project/playwright/), read 2026-11-26 - [Selenium documentation](https://www.selenium.dev/documentation/), [getting started](https://www.selenium.dev/documentation/webdriver/getting_started/) and [waits](https://www.selenium.dev/documentation/webdriver/waits/), read 2026-11-26 - [Selenium Grid](https://www.selenium.dev/documentation/grid/), read 2026-11-26 - [docker-selenium](https://github.com/SeleniumHQ/docker-selenium) and [Selenium releases](https://github.com/SeleniumHQ/selenium/releases), read 2026-11-26 - [pytest-xdist distribution](https://pytest-xdist.readthedocs.io/en/stable/distribution.html), read 2026-11-26 ## FAQ ### Is Playwright faster than Selenium? Neither project publishes a speed comparison, and run time depends far more on your pages, waits and parallelism than on the library. What differs by design is waiting, which Playwright does before every action and Selenium leaves to waits you write, and parallelism, which Playwright Test runs in worker processes out of the box. ### Which languages do Playwright and Selenium support? Playwright supports JavaScript and TypeScript, Python, Java and .NET. Selenium's official bindings are Java, Python, C#, Ruby, JavaScript and Kotlin. ### Can Playwright test Safari? Playwright tests WebKit, the engine behind Safari, on Linux, macOS and Windows. Selenium drives the Safari browser itself through its driver. ### Do I need Selenium Grid to run tests in parallel? Not on one machine; your test framework can run several sessions at once. Selenium Grid is for running sessions on remote machines and across browser versions and platforms. ### Should I migrate from Selenium to Playwright? Only with a reason the table supports, such as flaky waits, WebKit coverage or wanting a built-in runner. A large, stable Selenium suite on a working Grid keeps its value; mixed languages such as Ruby or Kotlin have no official Playwright binding. --- # Run browser tests in parallel: workers on one machine, shards across many URL: https://www.agentsandbox.host/p/run-browser-tests-in-parallel/ Author: AgentSandbox.host editors Published: 2026-11-26 Updated: 2026-11-26 On one machine, run browser tests in parallel with Playwright Test's worker processes (by default half the logical CPU cores) or pytest-xdist. Across machines, split the suite with --shard=x/y, one shard per machine or sandbox, and set fullyParallel so shards get an even share. Running browser tests in parallel means two different things: more browsers at once on one machine, and splitting the suite across several machines. Each browser needs its own CPU and memory, so the first route stops where the machine runs out, and the second takes over. ## How do I run Playwright tests in parallel on one machine? Run them in Playwright Test's worker processes, which are on by default. Playwright: "All workers have identical environments and each starts its own browser", and workers are "OS processes, running independently, orchestrated by the test runner" ([Playwright parallelism](https://playwright.dev/docs/test-parallel), read 2026-11-26). The number of workers "Defaults to half of the number of logical CPU cores" ([Playwright TestConfig](https://playwright.dev/docs/api/class-testconfig), read 2026-11-26). 1. Set the worker count in the config or on the command line: ```ts // playwright.config.ts import { defineConfig } from '@playwright/test'; export default defineConfig({ fullyParallel: true, workers: process.env.CI ? 2 : undefined, }); ``` ``` npx playwright test --workers 4 ``` 2. Decide how fine to split. By default files run in parallel and tests inside a file run in order; `fullyParallel: true` runs every test in every file in parallel. A single file can opt in with `test.describe.configure({ mode: 'parallel' })` or stay in order with `mode: 'serial'`, where "If one of the serial tests fails, all subsequent tests are skipped" (Playwright parallelism, read 2026-11-26). 3. Give each worker its own data. `process.env.TEST_PARALLEL_INDEX` runs from 0 to workers minus 1; use it to pick a separate test account or database per worker. ## How do I run Python or Selenium tests in parallel on one machine? Run them in pytest-xdist processes. Playwright's Python guide gives `pip install pytest-xdist` and `pytest --numprocesses auto` ([Playwright Python test runners](https://playwright.dev/python/docs/test-runners), read 2026-11-26). The two counting modes differ: "With `-n auto`, pytest-xdist will use as many processes as your computer has physical CPU cores", and `-n logical` uses logical cores instead ([pytest-xdist distribution](https://pytest-xdist.readthedocs.io/en/stable/distribution.html), read 2026-11-26). `--dist loadfile` keeps a file's tests on one worker, which helps when they share expensive setup. ## How many browsers can one machine take? About one browser per CPU core is the documented ceiling. The defaults of the three tools agree: Table: Default and documented parallelism per machine | Tool | Default | Documented guidance | |---|---|---| | Playwright Test | Half the logical CPU cores | Playwright recommends `workers: 1` on CI "to prioritize stability and reproducibility" ([Playwright CI](https://playwright.dev/docs/ci)) | | pytest-xdist `-n auto` | One process per physical core | `--maxprocesses` caps the count | | docker-selenium Node | One session per container | Raise up to the processor count; "running more browser sessions than the available processors is not recommended" ([docker-selenium](https://github.com/SeleniumHQ/docker-selenium)) | Go past this and tests start to time out because pages render late, which looks like flakiness. Our guide to [fixing flaky browser tests](https://www.agentsandbox.host/p/fix-flaky-browser-tests/) shows how to tell the two apart. ## How do I split a suite across machines? Split it into shards with `--shard=x/y` and run one shard per machine. Playwright's example for four machines ([Playwright sharding](https://playwright.dev/docs/test-sharding), read 2026-11-26): ``` npx playwright test --shard=1/4 npx playwright test --shard=2/4 npx playwright test --shard=3/4 npx playwright test --shard=4/4 ``` "Playwright can only shard tests that can be run in parallel", so by default whole files are shared out. With `fullyParallel: true` tests are split one by one and the shards come out even. We ran a two-test project with `fullyParallel: true` and `--shard=1/2` on @playwright/test 1.65.1 on 26 November 2026, and the first shard ran exactly one of the two tests. The machines can come from three places, all running the same shard command: 1. **Promigence sandboxes forked from one snapshot.** Promigence's guide to snapshots shows `Sandbox.fork` starting several copies of a prepared sandbox and running a command in each with its own environment variables, in TypeScript or Python (Promigence snapshot and fork guide, read 2026-11-26). The guide's own words: "Every copy starts with the files the sandbox had when you took the snapshot", so a snapshot taken after `npm ci` and `npx playwright install` hands every shard a ready project, and the shard number goes in as a variable. Its FAQ gives how long a copy takes to start: "A copy takes 39 ms, and a hundred at once still land at 122 ms" (Promigence FAQ, read 2026-11-26), times Promigence measured server-side, not through the network (Promigence SWE-bench page, read 2026-11-26). The quickstart's `promigence run quote` prices the run before anything starts, and `--cap` turns that price into a hard limit (Promigence quickstart, read 2026-11-26). 2. **Your own machines or containers,** each running one shard command, for example the [official Playwright image in Docker](https://www.agentsandbox.host/p/run-playwright-tests-in-docker/). 3. **A Selenium Grid,** for Selenium suites: tests stay on one machine and send sessions to Nodes on many ([Selenium Grid](https://www.selenium.dev/documentation/grid/), read 2026-11-26). A sketch of the first route in TypeScript, using the calls from Promigence's guide; `SNAPSHOT_ID` is the id of a snapshot that already holds your project with `npm ci` and the browsers installed: ```ts import { PromigenceClient, Sandbox } from "@promigence/sdk"; const client = new PromigenceClient(); // reads PROMIGENCE_API_KEY const SHARDS = 4; const copies = await Sandbox.fork(process.env.SNAPSHOT_ID!, { client, count: SHARDS, spendCap: 2, timeoutMs: 30 * 60_000, }); const codes = await Promise.all( copies.map(async (sbx, i) => { const r = await sbx.commands.run( `cd /work/repo && npx playwright test --shard=${i + 1}/${SHARDS}`, { timeoutMs: 25 * 60_000, throwOnExit: false }, ); await sbx.kill(); return r.exitCode; }), ); process.exit(codes.every((c) => c === 0) ? 0 : 1); ``` Other hosted services also start many copies from one prepared state, and each states its own start time, timing its own interval (read 2026-11-26): - **AWS:** Amazon Bedrock AgentCore Runtime V2 prepares your container once and "restores that snapshot for each new instance", which AWS says "keeps cold starts fast and consistent regardless of concurrency or image size"; the page states no time (AgentCore Runtime documentation). AgentCore Browser, a managed browser your tests can drive, gives each session 1 vCPU and 4 GB (AgentCore quotas). - **Daytona:** "any number of new sandboxes can start from the same snapshot" (Daytona snapshots documentation), and its home page gives "Sub 90ms sandbox creation from code to execution" (Daytona home page). - **E2B:** "a single snapshot can be used to create many new sandboxes" (E2B snapshots documentation), and its template documentation says snapshots let it "load the sandbox in ~80ms any time later with all the processes already running" (E2B template documentation). - **Google Cloud:** Agent Sandbox on GKE assigns each claim a sandbox from a warm pool of pre-warmed ones, which "enables new sandboxes to be created in under a second" (GKE Agent Sandbox documentation), and a Pod snapshot can be the base for "multiple new sandboxes with the same initialized state" (GKE Pod snapshots documentation). - **Modal:** a filesystem snapshot is an Image, so "you can create multiple Sandboxes from the same snapshot" (Modal Sandbox snapshots guide), and "Modal Sandboxes start in under one second" (Modal Sandboxes page). ## How do I combine the reports from all shards? Combine them with the blob reporter and `merge-reports`. Set `reporter: process.env.CI ? 'blob' : 'html'`, copy every shard's `blob-report` folder into one directory, then run (Playwright sharding, read 2026-11-26): ``` npx playwright merge-reports --reporter html ./all-blob-reports ``` The result is one HTML report for the whole suite, as if it had run on a single machine. ## What we read for this article - Promigence snapshot and fork guide, [https://www.promigence.ai/docs/guides/snapshot-and-fork](https://www.promigence.ai/docs/guides/snapshot-and-fork), read 2026-11-26 - Promigence quickstart, [https://www.promigence.ai/docs/quickstart](https://www.promigence.ai/docs/quickstart), read 2026-11-26 - Promigence FAQ, [https://www.promigence.ai/faq](https://www.promigence.ai/faq), read 2026-11-26 - Promigence SWE-bench page, [https://www.promigence.ai/for/swe-bench](https://www.promigence.ai/for/swe-bench), read 2026-11-26 - [Amazon Bedrock AgentCore Runtime documentation](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-how-it-works.html) and [AgentCore quotas](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/bedrock-agentcore-limits.html), read 2026-11-26 - [Daytona snapshots documentation](https://www.daytona.io/docs/en/snapshots) and [Daytona home page](https://www.daytona.io/), read 2026-11-26 - [E2B snapshots documentation](https://docs.e2b.dev/sandbox/snapshots) and [E2B template documentation](https://docs.e2b.dev/template/how-it-works), read 2026-11-26 - [GKE Agent Sandbox documentation](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/agent-sandbox) and [GKE Pod snapshots documentation](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/agent-sandbox-pod-snapshots), read 2026-11-26 - [Modal Sandbox snapshots guide](https://modal.com/docs/guide/sandbox-snapshots) and [Modal Sandboxes page](https://modal.com/products/sandboxes), read 2026-11-26 - [Playwright parallelism](https://playwright.dev/docs/test-parallel), read 2026-11-26 - [Playwright TestConfig](https://playwright.dev/docs/api/class-testconfig), read 2026-11-26 - [Playwright sharding](https://playwright.dev/docs/test-sharding), read 2026-11-26 - [Playwright CI](https://playwright.dev/docs/ci), read 2026-11-26 - [Playwright Python test runners](https://playwright.dev/python/docs/test-runners), read 2026-11-26 - [pytest-xdist distribution](https://pytest-xdist.readthedocs.io/en/stable/distribution.html), read 2026-11-26 - [docker-selenium](https://github.com/SeleniumHQ/docker-selenium), read 2026-11-26 - [Selenium Grid](https://www.selenium.dev/documentation/grid/), read 2026-11-26 ## FAQ ### How many Playwright workers should I use? Start from the default, half the logical CPU cores, and lower it if tests time out under load. Playwright recommends one worker on CI machines for stability and reproducibility; to finish sooner there, shard the suite across machines. ### What is the difference between workers and shards in Playwright? Workers are processes on one machine, each with its own browser. Shards split the test list across separate runs, usually on separate machines; each shard then uses its own workers. ### Why are my Playwright shards uneven? Without fullyParallel, Playwright shards whole files, so one large file lands on one shard. Set fullyParallel true to split by test, or keep files small and similar in size. ### How do I run pytest Playwright tests in parallel? Install pytest-xdist and run pytest --numprocesses auto, which starts one process per physical CPU core. Use -n logical to count logical cores instead. --- # Run Playwright tests in Docker with the official image URL: https://www.agentsandbox.host/p/run-playwright-tests-in-docker/ Author: AgentSandbox.host editors Published: 2026-11-26 Updated: 2026-11-26 Run Playwright tests in Docker from the official image tagged with your exact Playwright version, such as mcr.microsoft.com/playwright:v1.65.1-noble, with --init and --ipc=host, then npm ci and npx playwright test inside it. The image has the browsers but not your Playwright package. The official Playwright Docker image is a ready-made Linux environment with Node.js, the Playwright browsers and every system library they need. It is the quickest way to make browser tests run the same on a laptop and on any machine with Docker. Playwright describes it as "intended to be used for testing and development purposes only" ([Playwright Docker](https://playwright.dev/docs/docker), read 2026-11-26). ## What is in the official Playwright image? The image holds Node.js, the browsers and the browsers' system dependencies, and not your Playwright package. Playwright: "The Playwright package/dependency is not included in the image and should be installed separately" (Playwright Docker, read 2026-11-26). The 1.65.1 image's build file shows the details: it installs Node.js 26 and git on Ubuntu, creates a `pwuser` account and sets `PLAYWRIGHT_BROWSERS_PATH=/ms-playwright`, where the browser builds live ([Playwright Dockerfile.noble at v1.65.1](https://github.com/microsoft/playwright/blob/v1.65.1/utils/docker/Dockerfile.noble), read 2026-11-26). Table: Official Playwright image tags for release 1.65.1 | Tag | Base | Notes | |---|---|---| | `v1.65.1-noble` | Ubuntu 24.04 LTS (Noble Numbat) | Node.js image | | `v1.65.1-jammy` | Ubuntu 22.04 LTS (Jammy Jellyfish) | Node.js image | | `v1.65.1-resolute` | Newer Ubuntu base | Listed in the registry, not on the docs page | | `playwright/python:v1.65.2-noble` | Ubuntu 24.04 | The Python image, with Python's own version number | The tags come from the image registry's tag list for `playwright` and `playwright/python` ([image registry tag list](https://mcr.microsoft.com/v2/playwright/tags/list), read 2026-11-26). Each tag also has `-amd64` and `-arm64` variants. The docs page still shows `v1.64.1`; the 1.65 images were already published when we checked. ## Where can the image run? The image can run anywhere Docker images run. Three common places, each with the same image: 1. **On Promigence, as a verified snapshot.** Promigence's quickstart builds a snapshot from a container image you name, with setup steps and a verify command, and "If verify does not exit zero, nothing is stored" (Promigence quickstart, read 2026-11-26). Its CLI reference adds that a tag given to `--image` "is pinned to its digest for you", and that the same command builds from "an image, a Dockerfile, a devcontainer.json, a git repository or a local directory" (Promigence CLI reference, read 2026-11-26). For an image in a private registry, its errors page says to name a stored secret that holds the registry's user and password (Promigence errors page, read 2026-11-26). With the Playwright image as the base and your test command as the verify step, a stored snapshot is one in which the browsers have already started and passed your suite: ``` COMMIT=$(git rev-parse HEAD) promigence snapshot create \ --image mcr.microsoft.com/playwright:v1.65.1-noble \ --setup "git clone https://github.com/your-org/your-app /work/repo && git -C /work/repo checkout $COMMIT" \ --setup "cd /work/repo && npm ci" \ --verify "cd /work/repo && npx playwright test" \ --tier small --alias e2e --wait --wait-timeout 10m ``` Pin the commit, as here: the quickstart notes that "a snapshot built from a moving ref is not reproducible". 2. **On your own machine or server, with `docker run`.** The steps below. 3. **As the base of your own image.** A `FROM` line plus your project, also below. Other hosted services start from a container image as well, each with its own rules for where the image may come from and how a build is checked (read 2026-11-26): - **AWS:** Amazon Bedrock AgentCore Runtime runs a container image you build and push to Amazon ECR. On platform version V2 it snapshots the container when its health check first passes, and a health check that does not pass in time fails the deployment (AgentCore Runtime documentation). - **Daytona:** a snapshot can come from "any publicly accessible image or container registry" and needs a tag or digest, so a pinned tag such as `v1.65.1-noble` meets its rule; `latest`, `lts` and `stable` are refused (Daytona snapshots documentation). - **E2B:** a template's `fromImage()` accepts "any Docker image from Docker Hub or other registries" on a Debian, Ubuntu, Fedora, RHEL-family, Arch or Alpine base, and an unsupported image fails the build with an error that names the reason (E2B base image documentation). - **Google Cloud:** Cloud Run deploys images straight from Artifact Registry, Docker Hub or GitHub Container Registry; an image on another registry, such as the Playwright one, goes through an Artifact Registry remote repository (Cloud Run deploying documentation). - **Modal:** `modal.Image.from_registry()` builds a Sandbox's image from an external registry image with a fixed tag (Modal Sandboxes guide). ## How do I run my tests in the image with docker run? Mount your project, install its packages inside the container, and run the tests. 1. Check your Playwright version, and pick the tag that matches it: ``` npx playwright --version ``` 2. Run the container with the recommended flags. Playwright's command is `docker run -it --rm --ipc=host mcr.microsoft.com/playwright:v1.64.1-noble /bin/bash` (Playwright Docker, read 2026-11-26). For a one-shot test run with the 1.65.1 image: ``` docker run --rm --init --ipc=host \ -v "$PWD":/work -w /work \ mcr.microsoft.com/playwright:v1.65.1-noble \ /bin/bash -c "npm ci && npx playwright test" ``` 3. Read the results in `playwright-report` and `test-results` in your project folder; the mount writes them back to the host. Each flag has a documented reason: - `--ipc=host`: "Using `--ipc=host` is recommended when using Chromium. Without it, Chromium can run out of memory and crash" (Playwright Docker, read 2026-11-26). - `--init`: "recommended to avoid special treatment for processes with PID=1. This is a common reason for zombie processes." - `npm ci` inside the container, never your host's `node_modules`: packages with native parts are built for the host's system, and the container's is Linux. ## Why must the image version match my Playwright version? The image version must match because each Playwright release looks for its own browser builds. Playwright: "Each version of Playwright needs specific versions of browser binaries to operate" ([Playwright browsers](https://playwright.dev/docs/browsers), read 2026-11-26). If the image is 1.65.1 and your lock file says 1.64.0, the tests look for browsers the image does not have. Update the tag in the same change that updates `@playwright/test`. ## How do I build my own image on top of it? Start `FROM` the matching tag, copy the lock file first so the install layer is cached, then copy the rest: ```dockerfile FROM mcr.microsoft.com/playwright:v1.65.1-noble WORKDIR /work COPY package.json package-lock.json ./ RUN npm ci COPY . . CMD ["npx", "playwright", "test"] ``` Run it with the same flags: `docker build -t my-e2e .` then `docker run --rm --init --ipc=host my-e2e`. If you need a different Node.js or base image, Playwright lists what to install yourself: "you need to have Node.js, Playwright browsers and browser system dependencies installed", for example with `RUN npx -y playwright@1.64.1 install --with-deps` on a Node.js base (Playwright Docker, read 2026-11-26). ## Should the tests run as root in the container? Running as root is fine for testing your own app, and the image does so by default; use `pwuser` for anything untrusted. Playwright's Docker page explains that by default the browsers run as root, which disables the Chromium sandbox, and recommends a separate user with a custom system-call profile for crawling and scraping. For tests against your own application, root in a throwaway container is the documented default. ## How do I keep the browsers in the container and run tests from outside? Run Playwright's browser server in the container and connect to it from your machine. Playwright documents `npx -y playwright@1.64.1 run-server --port 3000 --host 0.0.0.0` inside the image, then setting `PW_TEST_CONNECT_WS_ENDPOINT` to the server's `ws://` address before `npx playwright test` (Playwright Docker, read 2026-11-26). The versions on both sides must match here too. This keeps your editor and test files on your machine while the browsers run in Linux. ## What we read for this article - Promigence quickstart, [https://www.promigence.ai/docs/quickstart](https://www.promigence.ai/docs/quickstart), read 2026-11-26 - Promigence CLI reference, [https://www.promigence.ai/docs/cli](https://www.promigence.ai/docs/cli), read 2026-11-26 - Promigence errors page, [https://www.promigence.ai/docs/errors](https://www.promigence.ai/docs/errors), read 2026-11-26 - [Amazon Bedrock AgentCore Runtime documentation](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-how-it-works.html), read 2026-11-26 - [Daytona snapshots documentation](https://www.daytona.io/docs/en/snapshots), read 2026-11-26 - [E2B base image documentation](https://docs.e2b.dev/template/base-image), read 2026-11-26 - [Cloud Run deploying documentation](https://docs.cloud.google.com/run/docs/deploying), read 2026-11-26 - [Modal Sandboxes guide](https://modal.com/docs/guide/sandbox), read 2026-11-26 - [Playwright Docker](https://playwright.dev/docs/docker), read 2026-11-26 - [Playwright Dockerfile.noble at v1.65.1](https://github.com/microsoft/playwright/blob/v1.65.1/utils/docker/Dockerfile.noble), read 2026-11-26 - [Playwright browsers](https://playwright.dev/docs/browsers), read 2026-11-26 - [Playwright continuous integration](https://playwright.dev/docs/ci), read 2026-11-26 - [Image registry tag list for playwright](https://mcr.microsoft.com/v2/playwright/tags/list), read 2026-11-26 ## FAQ ### Which Playwright Docker image tag should I use? The tag whose version matches the @playwright/test or playwright version in your lock file, on the Ubuntu base you want. For 1.65.1 that is v1.65.1-noble (Ubuntu 24.04) or v1.65.1-jammy (Ubuntu 22.04). ### Why does Chromium crash in the Playwright Docker image? Usually because the container's shared memory is too small. Playwright recommends --ipc=host for Chromium; without it, Chromium can run out of memory and crash. ### Does the Playwright Docker image include Playwright? No. The image includes Node.js, the browsers and their system dependencies, but the Playwright package must be installed from your project, for example with npm ci. ### Is there a Playwright image for Python? Yes. The Python image is published as mcr.microsoft.com/playwright/python with the same version tags, such as v1.65.2-noble. ### Can I run headed tests in the Playwright image? Yes. Playwright's CI guide says headed runs on Linux need Xvfb and that the Playwright Docker image includes it, so prefix the command with xvfb-run. --- # Selenium Grid: what it is and how to run it in Docker URL: https://www.agentsandbox.host/p/selenium-grid-docker/ Author: AgentSandbox.host editors Published: 2026-11-26 Updated: 2026-11-26 Selenium Grid runs WebDriver tests on remote browsers by routing each session from one address to Nodes that host the browsers. In Docker, start selenium/standalone-chrome for one container, or a selenium/hub with selenium/node-* containers for a real Grid, each with 2 GB of shared memory. Selenium Grid is the part of the Selenium project that "allows the execution of WebDriver scripts on remote machines" by "routing commands sent by the client to remote browser instances" ([Selenium Grid](https://www.selenium.dev/documentation/grid/), read 2026-11-26). The Selenium project publishes Docker images for every part of it, so a Grid can run on one laptop or across many machines with the same commands. ## What problem does Selenium Grid solve? Selenium Grid solves running browser tests somewhere other than the test machine. The Selenium docs name three goals: running tests in parallel across multiple machines, testing on different browser versions, and testing across platforms (Selenium Grid, read 2026-11-26). Your tests talk to one address; the Grid decides which browser serves each session. ## What are the parts of a Selenium Grid? A Selenium Grid has six components, each defined in the Selenium docs ([Selenium Grid components](https://www.selenium.dev/documentation/grid/components/), read 2026-11-26): Table: Selenium Grid components and what each does | Component | What it does | |---|---| | Router | "the entry point of the Grid, receiving all external requests" | | Distributor | Has two jobs: "Register and keep track of all Nodes and their capabilities", and "Query the New Session Queue and process any pending new session requests" | | Session Map | A data store that maps each session id to whichever Node runs that session | | New Session Queue | "holds all the new session requests in a FIFO order" | | Event Bus | The communication path between Nodes, the Distributor, the New Session Queue and the Session Map | | Node | "manages the slots for the available browsers of the machine where it is running" | You rarely run the six separately. Selenium offers three ways to start them: `standalone` (everything in one process), `hub` plus one or more `node` processes, or each component on its own for large installations ([Selenium Grid getting started](https://www.selenium.dev/documentation/grid/getting_started/), read 2026-11-26). Outside Docker, the server needs "Java 11 or higher installed". ## How do I run Selenium Grid in Docker in one container? Run the standalone image, which holds a Grid and one browser in one container. The docker-selenium project's command, with the tag current on 26 November 2026 ([docker-selenium](https://github.com/SeleniumHQ/docker-selenium), read 2026-11-26): ``` docker run -d -p 4444:4444 -p 7900:7900 --shm-size="2g" selenium/standalone-chrome:4.54.0-20261124 ``` 1. Port 4444 is where tests connect and where the Grid UI is served. 2. Port 7900 lets you watch the browser from your own browser; the README's address for it uses the password `secret`. 3. `--shm-size="2g"` gives the browser enough shared memory. The README explains: "This is a known workaround to avoid the browser crashing inside a docker container", and "The shm size of 2gb is arbitrary but known to work well". 4. The full tag pins both versions: "Always use a Docker image with a full tag to pin a specific browser and Grid version." ## How do I run a Hub and Nodes with Docker Compose? Run a Hub with Node containers on one Docker network; each Node finds the Hub through `SE_EVENT_BUS_HOST`. This is the project's own `docker-compose-v3.yml`, unchanged apart from comments ([docker-selenium compose file](https://github.com/SeleniumHQ/docker-selenium/blob/trunk/docker-compose-v3.yml), read 2026-11-26): ```yaml services: chrome: image: selenium/node-chrome:4.54.0-20261124 platform: linux/amd64 shm_size: 2gb depends_on: - selenium-hub environment: - SE_EVENT_BUS_HOST=selenium-hub edge: image: selenium/node-edge:4.54.0-20261124 platform: linux/amd64 shm_size: 2gb depends_on: - selenium-hub environment: - SE_EVENT_BUS_HOST=selenium-hub firefox: image: selenium/node-firefox:4.54.0-20261124 shm_size: 2gb depends_on: - selenium-hub environment: - SE_EVENT_BUS_HOST=selenium-hub selenium-hub: image: selenium/hub:4.54.0-20261124 container_name: selenium-hub ports: - "4442:4442" - "4443:4443" - "4444:4444" ``` Start it with `docker compose -f docker-compose-v3.yml up -d` and stop it with `docker compose -f docker-compose-v3.yml down`. To run more browsers, scale a service, for example `docker compose -f docker-compose-v3.yml up -d --scale chrome=4`. To put Nodes on other machines, expose the Event Bus. The Selenium docs: "it is important to expose the Event Bus ports (4442 and 4443 by default) on the Hub machine" (Selenium Grid getting started, read 2026-11-26). ## How do my tests connect to the Grid? Point a Remote WebDriver at port 4444 of the machine running the Grid. In Python (`pip install selenium`), using the `webdriver.Remote` call from the Selenium docs ([Selenium Remote WebDriver](https://www.selenium.dev/documentation/webdriver/drivers/remote_webdriver/), read 2026-11-26): ```python from selenium import webdriver GRID_URL = "http://grid-host:4444" # the machine running the Grid options = webdriver.ChromeOptions() driver = webdriver.Remote(command_executor=GRID_URL, options=options) try: driver.get("https://www.selenium.dev") print(driver.title) finally: driver.quit() ``` In JavaScript (`npm install selenium-webdriver`), the docs use `new Builder().forBrowser(Browser.CHROME).usingServer(gridUrl).build()`. Always call `quit()`: a session left open keeps its slot until the Grid times it out. ## How many sessions can each Node run? Each docker-selenium Node runs one session by default. The README: "By default, only one session is configured to run per container through the `SE_NODE_MAX_SESSIONS` environment variable. It is possible to increase that number up to the maximum available processors, this is because more stability is achieved when one container/browser has 1 CPU to run" ([docker-selenium README](https://github.com/SeleniumHQ/docker-selenium), read 2026-11-26). To go past the processor count you must also set `SE_NODE_OVERRIDE_MAX_SESSIONS=true`, and the project warns that "running more browser sessions than the available processors is not recommended since you will be overloading the resources". In practice, scale by adding Node containers, one browser and about one CPU each. ## Which images run on arm64? Since image tag 4.21.0 the project builds for amd64 and arm64 (docker-selenium README, read 2026-11-26). Chrome, Chromium and Firefox images are multi-arch; Edge and Chrome for Testing images are amd64 only. The README also says that "Running an AMD64 image under emulation on an ARM64 platform is not recommended", which is why the compose file above pins `platform: linux/amd64` on the Chrome and Edge services. On an arm64 machine, use `selenium/node-chromium` or `selenium/standalone-chromium` instead. For a comparison of Grid with Playwright's own way of scaling out, see [Playwright vs Selenium](https://www.agentsandbox.host/p/playwright-vs-selenium/). ## What we read for this article - [Selenium Grid](https://www.selenium.dev/documentation/grid/), read 2026-11-26 - [Selenium Grid components](https://www.selenium.dev/documentation/grid/components/), read 2026-11-26 - [Selenium Grid getting started](https://www.selenium.dev/documentation/grid/getting_started/), read 2026-11-26 - [Selenium Remote WebDriver](https://www.selenium.dev/documentation/webdriver/drivers/remote_webdriver/), read 2026-11-26 - [docker-selenium README](https://github.com/SeleniumHQ/docker-selenium), read 2026-11-26 - [docker-selenium compose file](https://github.com/SeleniumHQ/docker-selenium/blob/trunk/docker-compose-v3.yml), read 2026-11-26 ## FAQ ### What port does Selenium Grid use? Tests connect on port 4444, which also serves the Grid UI. In a Hub and Node setup the Event Bus uses ports 4442 and 4443, which must be reachable from every Node. ### Why do Selenium Docker images need --shm-size=2g? Browsers crash in a container whose shared memory is too small. The docker-selenium project calls 2 GB a known workaround that is arbitrary but known to work well, and says to tune it for your workload. ### How many browsers can one Selenium Node container run? One session by default, set by SE_NODE_MAX_SESSIONS. It can be raised up to the number of available processors; going higher needs SE_NODE_OVERRIDE_MAX_SESSIONS=true, and the project advises against more sessions than processors. ### Do Selenium Docker images run on arm64? Yes, from image tag 4.21.0 onwards for amd64 and arm64. Chrome, Chromium and Firefox images are multi-arch; Edge and Chrome for Testing images are amd64 only. ### How do I watch a test running inside a Selenium container? Publish port 7900 and open it in a browser; the docker-selenium README gives the password secret. --- # Testcontainers for browser tests: Selenium and Playwright in throwaway containers URL: https://www.agentsandbox.host/p/testcontainers-browser-tests/ Author: AgentSandbox.host editors Published: 2026-11-26 Updated: 2026-11-26 Testcontainers starts a browser in a throwaway Docker container from your test code and removes it afterwards. Its Selenium modules for Java, Python and Node.js hand you a WebDriver on a fresh browser; for Playwright, a generic container running the official browser server does the same. Testcontainers is an open-source library that starts Docker containers from inside your tests and removes them when the tests end. For browser tests it means each run gets a browser from a fixed image instead of whatever is installed on the machine. The Java documentation puts the benefit plainly: "Browsers are always launched from a fixed, clean image", and "the use of a clean browser prevents leakage of cookies, cached data or other state between tests" ([Testcontainers for Java: WebDriver containers](https://java.testcontainers.org/modules/webdriver_containers/), read 2026-11-26). ## When is Testcontainers the right tool for browser tests? Testcontainers fits when the test code itself should own the browser's lifecycle: a developer runs one test file and the browser appears, runs, and disappears. It needs only Docker on the machine. Table: Testcontainers compared with a standing Selenium Grid or a local browser | Setup | Who starts the browser | Good for | |---|---|---| | Testcontainers | The test, per test class or session | Same browser image everywhere; integration suites that already start a database container | | A standing Selenium Grid | An operator, once | Many teams and suites sharing a fleet of browsers | | A local browser install | Nobody; it is just there | Quick local runs where version drift does not matter | For the standing option, see our guide to [Selenium Grid in Docker](https://www.agentsandbox.host/p/selenium-grid-docker/). ## How do I use the Selenium module in Python? Install the Selenium extra, then open the container in a `with` block and ask it for a driver. 1. Install the packages. The `selenium` extra is listed among the extras of testcontainers 4.15.0 on PyPI ([PyPI: testcontainers](https://pypi.org/project/testcontainers/), read 2026-11-26): ``` pip install "testcontainers[selenium]" ``` 2. Start a browser and use it. The two calls come from the module's example ([testcontainers-python Selenium module](https://testcontainers-python.readthedocs.io/en/latest/modules/selenium/README.html), read 2026-11-26): ```python from selenium.webdriver import DesiredCapabilities from testcontainers.selenium import BrowserWebDriverContainer with BrowserWebDriverContainer(DesiredCapabilities.CHROME) as chrome: webdriver = chrome.get_driver() webdriver.get("https://www.selenium.dev") print(webdriver.title) ``` Pass `DesiredCapabilities.FIREFOX` for Firefox. In pytest, put the `with` block in a session-scoped fixture so the container starts once per run instead of once per test. ## How do I use the Selenium module in Node.js? Install the module and the WebDriver client, start a `SeleniumContainer` with an image, and build a driver against its URL. The install commands are from the module's page ([Testcontainers for Node.js: Selenium](https://node.testcontainers.org/modules/selenium/), read 2026-11-26): ``` npm install @testcontainers/selenium --save-dev npm install selenium-webdriver npm install @types/selenium-webdriver --save-dev ``` The key lines of the module's own example, with an image tag from the docker-selenium project: ```ts import { SeleniumContainer } from "@testcontainers/selenium"; import { Browser, Builder } from "selenium-webdriver"; await using container = await new SeleniumContainer("selenium/standalone-chrome:4.54.0-20261124").start(); const driver = await new Builder().forBrowser(Browser.CHROME).usingServer(container.getServerUrl()).build(); await driver.get("https://testcontainers.com"); console.log(await driver.getTitle()); await driver.quit(); ``` `await using` stops and removes the container when the block ends. For a video, start the container with `.withRecording()`, stop it, and call `saveRecording(path)` on the stopped container (Testcontainers for Node.js: Selenium, read 2026-11-26). The current release of `testcontainers` on npm was 12.2.2, which declares Node.js 22.22 or newer ([npm: testcontainers](https://www.npmjs.com/package/testcontainers), read 2026-11-26). ## How do I use the WebDriver module in Java? Create a `BrowserWebDriverContainer` with a docker-selenium image and connect a `RemoteWebDriver` to its address. The module's documented calls (Testcontainers for Java: WebDriver containers, read 2026-11-26): ```java BrowserWebDriverContainer chrome = new BrowserWebDriverContainer("selenium/standalone-chrome:4.54.0-20261124"); chrome.start(); RemoteWebDriver driver = new RemoteWebDriver(chrome.getSeleniumAddress(), new ChromeOptions()); ``` The dependency is `org.testcontainers:testcontainers-selenium:2.0.5` in test scope, plus Selenium itself, which "the Testcontainers JAR doesn't add". To record, add `.withRecordingMode(VncRecordingMode.RECORD_FAILING, target)` for failing tests only, or `RECORD_ALL`. ## How does the browser reach an app running on my machine? Expose the app's port to containers, then browse to `host.testcontainers.internal`. Java: `Testcontainers.exposeHostPorts(localPort)` and then `driver.get("http://host.testcontainers.internal:" + localPort)` (Testcontainers for Java: WebDriver containers, read 2026-11-26). Node.js: `await TestContainers.exposeHostPorts(8000)`, after which containers reach the port at `host.testcontainers.internal:8000` ([Testcontainers for Node.js: networking](https://node.testcontainers.org/features/networking/), read 2026-11-26). ## How do I run Playwright browsers with Testcontainers? Run the official Playwright image as a generic container that starts Playwright's browser server, then connect to it. The example below is ours, assembled from documented calls: `GenericContainer`, `withCommand`, `withExposedPorts`, `withIpcMode` and `getMappedPort` from Testcontainers ([Testcontainers for Node.js: containers](https://node.testcontainers.org/features/containers/), read 2026-11-26), and `run-server` and `connect` from Playwright ([Playwright Docker](https://playwright.dev/docs/docker), read 2026-11-26). ```ts import { GenericContainer } from "testcontainers"; import { chromium } from "@playwright/test"; const PW = "1.65.1"; // must equal the @playwright/test version in your lock file const server = await new GenericContainer(`mcr.microsoft.com/playwright:v${PW}-noble`) .withCommand(["npx", "-y", `playwright@${PW}`, "run-server", "--port", "3000", "--host", "0.0.0.0"]) .withExposedPorts(3000) .withIpcMode("host") .start(); const browser = await chromium.connect(`ws://${server.getHost()}:${server.getMappedPort(3000)}/`); const page = await browser.newPage(); await page.goto("https://playwright.dev"); console.log(await page.title()); await browser.close(); await server.stop(); ``` Three details make it work: 1. **Matching versions.** The client and the server must be the same Playwright release, which is why one constant sets both. 2. **Waiting for the server.** By default Testcontainers "waits up to 60 seconds for mapped network ports to be bound" ([Testcontainers for Node.js: wait strategies](https://node.testcontainers.org/features/wait-strategies/), read 2026-11-26). The first start also downloads the package with `npx`; bake it into your own image if that time matters. 3. **Shared memory.** `withIpcMode("host")` follows Playwright's advice for Chromium; `withSharedMemorySize(bytes)` is the alternative when you would rather keep the container's IPC private. With Playwright Test, you can instead set `PW_TEST_CONNECT_WS_ENDPOINT` to the server's address, as Playwright's Docker page describes, and keep your tests unchanged. ## How do I make container start-up cheaper across runs? Start containers once per session rather than once per test, and pin image tags so they are pulled once. Testcontainers for Node.js also offers `.withReuse()`, which means "Testcontainers will not start a new container" when a matching one is already running; it is controlled globally by `TESTCONTAINERS_REUSE_ENABLE` (Testcontainers for Node.js: containers, read 2026-11-26). A reused browser container keeps no state between tests only if each test opens a new session or context. ## What we read for this article - [Testcontainers for Java: WebDriver containers](https://java.testcontainers.org/modules/webdriver_containers/), read 2026-11-26 - [testcontainers-python Selenium module](https://testcontainers-python.readthedocs.io/en/latest/modules/selenium/README.html), read 2026-11-26 - [Testcontainers for Node.js: Selenium](https://node.testcontainers.org/modules/selenium/), read 2026-11-26 - [Testcontainers for Node.js: containers](https://node.testcontainers.org/features/containers/), read 2026-11-26 - [Testcontainers for Node.js: networking](https://node.testcontainers.org/features/networking/), read 2026-11-26 - [Testcontainers for Node.js: wait strategies](https://node.testcontainers.org/features/wait-strategies/), read 2026-11-26 - [Playwright Docker](https://playwright.dev/docs/docker), read 2026-11-26 - [PyPI: testcontainers](https://pypi.org/project/testcontainers/), read 2026-11-26 - [npm: testcontainers](https://www.npmjs.com/package/testcontainers), read 2026-11-26 ## FAQ ### What is Testcontainers? Testcontainers is an open-source library, available for Java, Python, Node.js and other languages, that starts Docker containers from test code and cleans them up when the test ends. It is used for databases, message brokers and browsers. ### Does Testcontainers have a Playwright module? The official Selenium modules cover WebDriver. For Playwright, start the official Playwright image as a generic container running Playwright's browser server, and connect to it from your test. ### How does a browser in a Testcontainers container reach my app on localhost? Expose the app's port to containers with exposeHostPorts, then open host.testcontainers.internal and that port from the browser. Both the Java and Node.js libraries document this. ### Can Testcontainers record a video of a browser test? Yes. The Java module records with withRecordingMode, for all tests or only failing ones, and the Node.js Selenium module records with withRecording and saveRecording. --- # About AgentSandbox.host is a working guide to running browser tests at scale: getting Playwright going in Python and Node.js, choosing between Playwright and Selenium, running browsers in containers and on a Selenium Grid, splitting a suite across many workers and machines, and keeping the results trustworthy. Guides are written and signed by the editors as a desk. Commands, defaults and version numbers are taken from each project's own documentation, release notes and package registry, and every guide lists what was read and when. Each guide carries the day it was published and the day it was last checked; when a release changes a command or a default, the guide is corrected in place. The guides are about open-source tools; where a hosted service appears as a worked example, its facts are quoted from its own published pages with the date, and nothing is ranked.