English · Python
Appearance
English · Python
Appearance
import LiteYouTube from '@site/src/components/LiteYouTube';
A locator from locator.normalize() now converts to a string as Python code. Use it with page.get_by_ref() to turn an element that an agent picks from a page.aria_snapshot() in the "ai" mode into code for your test:
normalized = page.get_by_ref("e2").normalize()
print(str(normalized))
# get_by_role("button", name="Submit")timeout in cdp_session.send().locator.click(), locator.check(), locator.tap(), locator.fill(), locator.clear() and locator.select_option() now wait for the element to be not inert. An action on an element with the inert attribute, or inside such an element, now times out if the element stays inert.browser_context.cookies() and api_request_context.cookies() no longer return host-only cookies for subdomains or Path=/api cookies for /apiv2, and a Path=/foo/ cookie does not match /foo. APIRequestContext sends a cookie without a name as Cookie: x instead of Cookie: =x, and stores Set-Cookie: token as a cookie without a name.proxy option now answer only proxy challenges. To authenticate on a website, use http_credentials.<details>, is no longer part of accessible names and aria snapshots. This can change the results of page.get_by_role() with a name, locator.aria_snapshot() and locator_assertions.to_match_aria_snapshot().params option in APIRequestContext requests are now appended to the query that the URL already has, instead of replacing it.libatomic.so.1. Minimal images, including python:*-slim, may need libatomic1 installed before running Playwright, including playwright install --with-deps.This version was also tested against the following stable channels:
New page.webmcp and frame.webmcp give access to the tools that a page registers through the experimental WebMCP browser API, so you can test them like any other part of your app:
browser = chromium.launch(args=["--enable-features=WebMCP"])
page = browser.new_page()
page.goto("https://example.com")
for tool in page.webmcp.tools():
print(tool["name"], tool["description"])
result = page.webmcp.call_tool("add", {"a": 2, "b": 40})
print(result["content"][0]["text"]) # "42"Playwright MCP also supports WebMCP by default, with page-defined tools offered to the agent as webmcp_<tool>. Pass --no-webmcp to opt out.
playwright-cli exposes them as well:
playwright-cli webmcp-list
playwright-cli webmcp-call search_catalog --params '{"query":"cats"}'Videos can now be recorded at a custom frame rate, and the decorations for actions are styled with plain CSS:
page.screencast.start(path="video.webm", size={"width": 1920, "height": 1080}, fps=60)
page.screencast.show_actions(
style={
"point": "width: 20px; height: 20px; border-radius: 50%; background: red",
"highlight": "outline: 2px solid #333; background: rgba(0, 128, 255, .15)",
"title": "font-size: 16px",
}
)record_video_fps option and new fps option in screencast.start(). Firefox and WebKit currently capture up to 25 frames per second.style option takes CSS declarations for the point marker, the target highlight and the action title. It replaces the font_size option, which is now deprecated.playwright-cli.New locator.within() combines two locators that you already have, reading in the natural order — "this button, within that dialog":
save_button = page.get_by_role("button", name="Save")
dialog = page.get_by_test_id("settings-dialog")
save_button.within(dialog).click()Relative locators such as locator.nth() or locator.first() are resolved inside each parent separately, which makes column-like queries straightforward:
# The third cell of every row, not the third cell in the table.
third_column = page.get_by_role("cell").nth(2).within(page.get_by_role("row"))
expect(third_column).to_have_text(["Apple", "Banana", "Cherry"])New page.get_by_ref() locates an element by its aria ref, such as e2, reported by page.aria_snapshot() in the "ai" mode.
New option include_shadow in page.content() and frame.content() serializes open shadow roots as declarative shadow DOM.
New option sign_count sets the initial signature counter of a virtual credential. credentials.create() and credentials.get() return the current sign_count, and it is saved and restored together with the credentials in the storage state.
New api_request_context.add_cookies(), api_request_context.cookies() and api_request_context.clear_cookies() manage cookies of a request context, mirroring the BrowserContext methods:
request.add_cookies(
[{"name": "session-id", "value": "42", "url": "https://example.com"}]
)
print(request.cookies("https://example.com"))
request.clear_cookies(name="session-id")visibility: hidden, are now considered hidden by actions, locator.is_visible() and locator_assertions.to_be_visible().This version was also tested against the following stable channels:
page.frame_locator() and frame.frame_locator() called without a selector search in any frame of the subtree, so you no longer need to locate the iframe first:
# Finds the button in any frame on the page.
page.frame_locator().get_by_role("button").click()The rest of the locator resolves inside a single frame, just like a regular locator, and an error is thrown when it matches elements in several frames.
New locator.visible() returns a locator that matches only visible elements. It is the recommended replacement for the :visible CSS pseudo-class:
page.locator("button").visible.click()New aria_snapshots and screen_snapshots options of tracing.start() capture an aria snapshot and a screenshot of the page on every action:
context.tracing.start(snapshots=True, aria_snapshots=True, screen_snapshots=True)With aria and screen snapshots recorded, the new Display Aria mode in the trace viewer shows the action screenshot side by side with the aria snapshot, and hovering an aria node highlights it on the screenshot.
http_credentials now also accepts an array of credentials. The first entry matching the request origin is used, and entries without an origin match any request.opfs includes the origin private file system in the storage state, so it can be persisted and restored into later contexts.page.on("dialogClosed") and browserContext.on("dialogClosed") are emitted when a JavaScript dialog is accepted, dismissed or closed by the user.playwright install --no-remove keeps the browsers of other Playwright installations instead of removing them.playwright codegen --http-credentials records against pages behind HTTP authentication.This version was also tested against the following stable channels:
page.screenshot() and locator.screenshot() can now capture screenshots in the WebP format — Playwright infers the format from a .webp file extension, or you can set the type explicitly. Quality 100 (the default) is lossless, while lower values use lossy compression:
page.screenshot(path="homepage.webp", quality=50)scroll option ("auto" | "none") on actions to opt out of Playwright's automatic scroll-into-view.locator.wait_for_function() waits until a function — called with the matching element — returns a truthy value.api_response.timing() returns resource timing information for an API response.navigator.clipboard no longer read or overwrite the clipboard of the machine running them.This version was also tested against the following stable channels:
New Credentials virtual authenticator, available via browser_context.credentials, lets tests register passkeys and answer navigator.credentials.create() / navigator.credentials.get() ceremonies in the page — no real hardware key required, works in all browsers:
context = browser.new_context()
# Seed a passkey your backend provisioned for a test user.
context.credentials.create("example.com",
id=credential_id,
user_handle=user_handle,
private_key=private_key,
public_key=public_key,
)
context.credentials.install()
page = context.new_page()
page.goto("https://example.com/login")
# The page's navigator.credentials.get() is answered with the seeded passkey.You can also let the app register a passkey once in a setup test, read it back with credentials.get(), and seed it into later tests — see Credentials for details.
New WebStorage API, available via page.local_storage and page.session_storage, reads and writes the page's storage for the current origin:
page.local_storage.set_item("token", "abc")
token = page.local_storage.get_item("token")
items = page.session_storage.items()api_response.security_details() and api_response.server_addr() mirror the browser-side response.security_details() and response.server_addr().artifacts_dir in browser_type.connect_over_cdp() controls where artifacts such as traces and downloads are stored when attached to an existing browser.cursor in screencast.show_actions() controls the cursor decoration rendered for pointer actions.on_frame callback in screencast.start() now receives a timestamp of when the frame was presented by the browser.This version was also tested against the following stable channels:
tracing.start_har() / tracing.stop_har() expose HAR recording as a first-class tracing API, with the same content, mode and url_filter options as record_har:
context.tracing.start_har("trace.har")
page = context.new_page()
page.goto("https://playwright.dev")
context.tracing.stop_har()New locator.drop() simulates an external drag-and-drop of files or clipboard-like data onto an element. Playwright dispatches dragenter, dragover, and drop with a synthetic [DataTransfer] in the page context — works cross-browser and is great for testing upload zones:
page.locator("#dropzone").drop(
files={"name": "note.txt", "mime_type": "text/plain", "buffer": b"hello"},
)
page.locator("#dropzone").drop(
data={
"text/plain": "hello world",
"text/uri-list": "https://example.com",
},
)page_assertions.to_match_aria_snapshot() now works on a Page, in addition to a Locator — equivalent to asserting against page.locator("body").boxes option on locator.aria_snapshot() / page.aria_snapshot() appends each element's bounding box as [box=x,y,width,height], useful for AI consumption.browser.on("context") — fired when a new context is created on the browser.browserContext.on("download"), browserContext.on("frameAttached"), browserContext.on("frameDetached"), browserContext.on("frameNavigated"), browserContext.on("pageClose"), browserContext.on("pageLoad").description in page.get_by_role() / locator.get_by_role() / frame.get_by_role() / frame_locator.get_by_role() for matching the accessible description.pseudo in locator_assertions.to_have_css() reads computed styles from ::before or ::after.style in locator.highlight() applies extra inline CSS to the highlight overlay, plus new page.hide_highlight() to clear all highlights.web_socket_route.protocols() returns the WebSocket subprotocols requested by the page.no_defaults in browser_type.connect_over_cdp() disables Playwright's default overrides on the default context (download behavior, focus emulation, media emulation), so attaching to a user's daily-driver browser doesn't disturb its state.web_error.location() mirrors console_message.location().console_message.location() now exposes line / column properties (line_number / column_number are deprecated).handle option on BrowserContext.expose_binding and Page.expose_binding.This version was also tested against the following stable channels:
New page.screencast API provides a unified interface for capturing page content with:
Screencast recording — record video with precise start/stop control, as an alternative to the record_video_dir option:
page.screencast.start(path="video.webm")
# ... perform actions ...
page.screencast.stop()Action annotations — enable built-in visual annotations that highlight interacted elements and display action titles during recording:
page.screencast.show_actions(position="top-right")screencast.show_actions() accepts position ('top-left', 'top', 'top-right', 'bottom-left', 'bottom', 'bottom-right'), duration (ms per annotation), and font_size (px). Returns a disposable to stop showing actions.
Visual overlays — add chapter titles and custom HTML overlays on top of the page for richer narration:
page.screencast.show_chapter("Adding TODOs",
description="Type and press enter for each TODO",
duration=1000,
)
page.screencast.show_overlay('<div style="color: red">Recording</div>')Real-time frame capture — stream JPEG-encoded frames for custom processing like thumbnails, live previews, AI vision, and more:
page.screencast.start(
on_frame=lambda frame: send_to_vision_model(frame["data"]),
)Agentic video receipts — coding agents can produce video evidence of their work. After completing a task, an agent can record a walkthrough video with rich annotations for human review:
page.screencast.start(path="receipt.webm")
page.screencast.show_actions(position="top-right")
page.screencast.show_chapter("Verifying checkout flow",
description="Added coupon code support per ticket #1234",
)
# Agent performs the verification steps...
page.locator("#coupon").fill("SAVE20")
page.locator("#apply-coupon").click()
expect(page.locator(".discount")).to_contain_text("20%")
page.screencast.show_chapter("Done",
description="Coupon applied, discount reflected in total",
)
page.screencast.stop()The resulting video serves as a receipt: chapter titles provide context, action annotations highlight each interaction, and the visual walkthrough is faster to review than text logs.
page.aria_snapshot() to capture the aria snapshot of the page — equivalent to page.locator('body').aria_snapshot().depth and mode in locator.aria_snapshot().locator.normalize() converts a locator to follow best practices like test ids and aria roles.page.pick_locator() enters an interactive mode where hovering over elements highlights them and shows the corresponding locator. Click an element to get its Locator back. Use page.cancel_pick_locator() to cancel.page.screencast provides video recording, real-time frame streaming, and overlay management.screencast.start() and screencast.stop() for recording and frame capture.screencast.show_actions() and screencast.hide_actions() for action annotations.screencast.show_chapter() and screencast.show_overlay() for visual overlays.screencast.show_overlays() and screencast.hide_overlays() for overlay visibility control.browser_context.set_storage_state() clears existing cookies, local storage, and IndexedDB for all origins and sets a new storage state — no need to create a new context.page.clear_console_messages() and page.clear_page_errors() to clear stored messages and errors.filter in page.console_messages() and page.page_errors() controls which messages are returned.console_message.timestamp().browser_context.debugger provides programmatic control over the Playwright debugger.browser_context.is_closed().request.existing_response() returns the response without waiting.response.http_version() returns the HTTP version used by the response.live in tracing.start() for real-time trace updates.artifacts_dir in browser_type.launch() to configure the artifacts directory.New browser.bind() API makes a launched browser available for playwright-cli, @playwright/mcp, and other clients to connect to.
Bind a browser — start a browser and bind it so others can connect:
server_info = await browser.bind("my-session",
workspace_dir="/my/project",
)Connect from playwright-cli — connect to the running browser from your favorite coding agent.
playwright-cli attach my-session
playwright-cli -s my-session snapshotConnect from @playwright/mcp — or point your MCP server to the running browser.
@playwright/mcp --endpoint=my-sessionConnect from a Playwright client — use API to connect to the browser. Multiple clients at a time are supported!
browser = await chromium.connect(server_info["endpoint"])Pass host and port options to bind over WebSocket instead of a named pipe:
server_info = await browser.bind("my-session",
host="localhost",
port=0,
)
# server_info["endpoint"] is a ws:// URLCall browser.unbind() to stop accepting new connections.
Run playwright-cli show to open the Dashboard that lists all the bound browsers, their statuses, and allows interacting with them:
This version was also tested against the following stable channels:
Thanks to @cpAdm for contributing these improvements!
browser_type.connect_over_cdp() now accepts an is_local option. When set to True, it tells Playwright that it runs on the same host as the CDP server, enabling file system optimizations.
_react and _vue selectors. See locators guide for alternatives.:light selector engine suffix. Use standard CSS selectors instead.devtools from browser_type.launch() has been removed. Use args=['--auto-open-devtools-for-tabs'] instead.This version was also tested against the following stable channels:
Playwright now runs on Chrome for Testing builds rather than Chromium. Headed mode uses chrome; headless mode uses chrome-headless-shell. Existing tests should continue to pass after upgrading to v1.57.
We're expecting no functional changes to come from this switch. The biggest change is the new icon and title in your toolbar.

If you still see an unexpected behaviour change, please file an issue.
On Arm64 Linux, Playwright continues to use Chromium.
After 3 years of being deprecated, we removed page.accessibility from our API. Please use other libraries such as Axe if you need to test page accessibility. See our Node.js guide for integration with Axe.
worker.on("console") event is emitted when JavaScript within the worker calls one of console API methods, e.g. console.log or console.dir. worker.expect_event() can be used to wait for it.locator.description() returns locator description previously set with locator.describe().steps in locator.click() and locator.drag_to() that configures the number of mousemove events emitted while moving the mouse pointer to the target element.PLAYWRIGHT_DISABLE_SERVICE_WORKER_NETWORK environment variable.worker.on("console"). You can opt out of this using the PLAYWRIGHT_DISABLE_SERVICE_WORKER_CONSOLE environment variable.page.console_messages() and page.page_errors() for retrieving the most recent console messages from the pagepage.requests() for retrieving the most recent network requests from the pagebrowserContext.on("backgroundPage") has been deprecated and will not be emitted. Method browser_context.background_pages() will return an empty listinput placeholderto_be_visible() assertions: Codegen can now generate automatic to_be_visible() assertions for common UI interactions. This feature can be enabled in the Codegen settings UI.This version was also tested against the following stable channels:
New cookie property partition_key in browser_context.cookies() and browser_context.add_cookies(). This property allows to save and restore partitioned cookies. See CHIPS MDN article for more information. Note that browsers have different support and defaults for cookie partitioning.
New option --user-data-dir in multiple commands. You can specify the same user data dir to reuse browsing state, like authentication, between sessions.
playwright codegen --user-data-dir=./user-dataplaywright open does not open the test recorder anymore. Use playwright codegen instead.
This version was also tested against the following stable channels:
New Steps in Trace Viewer:
New method locator.describe() to describe a locator. Used for trace viewer.
button = page.get_by_test_id("btn-sub").describe("Subscribe button")
button.click()python -m playwright install --list will now list all installed browsers, versions and locations.
This version was also tested against the following stable channels:
New method locator_assertions.to_contain_class() to ergonomically assert individual class names on the element.
expect(page.get_by_role('listitem', name='Ship v1.52')).to_contain_class('done')Aria Snapshots got two new properties: /children for strict matching and /url for links.
expect(locator).to_match_aria_snapshot("""
- list
- /children: equal
- listitem: Feature A
- listitem:
- link "Feature B":
- /url: "https://playwright.dev"
""")max_redirects in api_request.new_context() to control the maximum number of redirects.page.route() do not support ? and [] anymore. We recommend using regular expressions instead.route.continue_() does not allow to override the Cookie header anymore. If a Cookie header is provided, it will be ignored, and the cookie will be loaded from the browser's cookie store. To set custom cookies, use browser_context.add_cookies().This version was also tested against the following stable channels:
New option indexed_db for browser_context.storage_state() allows to save and restore IndexedDB contents. Useful when your application uses IndexedDB API to store authentication tokens, like Firebase Authentication.
Here is an example following the authentication guide:
# Save storage state into the file. Make sure to include IndexedDB.
storage = await context.storage_state(path="state.json", indexed_db=True)
# Create a new context with the saved storage state.
context = await browser.new_context(storage_state="state.json")New option visible for locator.filter() allows matching only visible elements.
# Ignore invisible todo items.
todo_items = page.get_by_test_id("todo-item").filter(visible=True)
# Check there are exactly 3 visible ones.
await expect(todo_items).to_have_count(3)New option contrast for methods page.emulate_media() and browser.new_context() allows to emulate the prefers-contrast media feature.
New option fail_on_status_code makes all fetch requests made through the APIRequestContext throw on response codes other than 2xx and 3xx.
This version was also tested against the following stable channels:
locator_assertions.to_have_accessible_error_message() to assert the Locator points to an element with a given aria errormessage.canvas content in traces is error-prone. Display is now disabled by default, and can be enabled via the Display canvas content UI setting.Call and Network panels now display additional time information.locator_assertions.to_be_editable() and locator.is_editable() now throw if the target element is not <input>, <select>, or a number of other editable elements.This version was also tested against the following stable channels:
New assertion locator_assertions.to_match_aria_snapshot() verifies page structure by comparing to an expected accessibility tree, represented as YAML.
page.goto("https://playwright.dev")
expect(page.locator('body')).to_match_aria_snapshot('''
- banner:
- heading /Playwright enables reliable/ [level=1]
- link "Get started"
- link "Star microsoft/playwright on GitHub"
- main:
- img "Browsers (Chromium, Firefox, WebKit)"
- heading "Any browser • Any platform • One API"
''')You can generate this assertion with Test Generator or by calling locator.aria_snapshot().
Learn more in the aria snapshots guide.
New method tracing.group() allows you to visually group actions in the trace viewer.
# All actions between group and group_end
# will be shown in the trace viewer as a group.
page.context.tracing.group("Open Playwright.dev > API")
page.goto("https://playwright.dev/")
page.get_by_role("link", name="API").click()
page.context.tracing.group_end()chrome and msedge channels switch to new headless mode This change affects you if you're using one of the following channels in your playwright.config.ts:
chrome, chrome-dev, chrome-beta, or chrome-canarymsedge, msedge-dev, msedge-beta, or msedge-canaryAfter updating to Playwright v1.49, run your test suite. If it still passes, you're good to go. If not, you will probably need to update your snapshots, and adapt some of your test code around PDF viewers and extensions. See issue #33566 for more details.
You can opt into the new headless mode by using 'chromium' channel. As official Chrome documentation puts it:
New Headless on the other hand is the real Chrome browser, and is thus more authentic, reliable, and offers more features. This makes it more suitable for high-accuracy end-to-end web app testing or browser extension testing.
See issue #33566 for the list of possible breakages you could encounter and more details on Chromium headless. Please file an issue if you see any problems after opting in.
pytest test_login.py --browser-channel chromium<canvas> elements inside a snapshot now draw a preview.This version was also tested against the following stable channels:
New methods page.route_web_socket() and browser_context.route_web_socket() allow to intercept, modify and mock WebSocket connections initiated in the page. Below is a simple example that mocks WebSocket communication by responding to a "request" with a "response".
def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
if message == "request":
ws.send("response")
page.route_web_socket("/ws", lambda ws: ws.on_message(
lambda message: message_handler(ws, message)
))See WebSocketRoute for more details.
route.fulfill() are not shown in the report and trace viewer anymore. You can see which network requests were routed in the network tab instead.page.request_gc() may help detect memory leaks.This version was also tested against the following stable channels:
The Network tab in the trace viewer has several nice improvements:
mcr.microsoft.com/playwright/python:v1.47.0 now serves a Playwright image based on Ubuntu 24.04 Noble. To use the 22.04 jammy-based image, please use mcr.microsoft.com/playwright/python:v1.47.0-jammy instead.:latest/:focal/:jammy tag for Playwright Docker images is no longer being published. Pin to a specific version for better stability and reproducibility.client_certificates.cert and client_certificates.key as bytes instead of file paths.no_wait_after in locator.select_option() was deprecated.macos-13. We recommend upgrading GitHub Actions to macos-14.This version was also tested against the following stable channels:
Playwright now allows to supply client-side certificates, so that server can verify them, as specified by TLS Client Authentication.
You can provide client certificates as a parameter of browser.new_context() and api_request.new_context(). The following snippet sets up a client certificate for https://example.com:
context = browser.new_context(
client_certificates=[
{
"origin": "https://example.com",
"certPath": "client-certificates/cert.pem",
"keyPath": "client-certificates/key.pem",
}
],
)route.continue_().base_url.maxRetries option in api_request_context.fetch() which retries on the ECONNRESET network error.This version was also tested against the following stable channels:
Utilizing the new Clock API allows to manipulate and control time within tests to verify time-related behavior. This API covers many common scenarios, including:
# Initialize clock with some time before the test time and let the page load
# naturally. `Date.now` will progress as the timers fire.
page.clock.install(time=datetime.datetime(2024, 2, 2, 8, 0, 0))
page.goto("http://localhost:3333")
# Pretend that the user closed the laptop lid and opened it again at 10am.
# Pause the time once reached that point.
page.clock.pause_at(datetime.datetime(2024, 2, 2, 10, 0, 0))
# Assert the page state.
expect(page.get_by_test_id("current-time")).to_have_text("2/2/2024, 10:00:00 AM")
# Close the laptop lid again and open it at 10:30am.
page.clock.fast_forward("30:00")
expect(page.get_by_test_id("current-time")).to_have_text("2/2/2024, 10:30:00 AM")See the clock guide for more details.
Method locator.set_input_files() now supports uploading a directory for <input type=file webkitdirectory> elements.
page.get_by_label("Upload directory").set_input_files('mydir')Multiple methods like locator.click() or locator.press() now support a ControlOrMeta modifier key. This key maps to Meta on macOS and maps to Control on Windows and Linux.
# Press the common keyboard shortcut Control+S or Meta+S to trigger a "Save" operation.
page.keyboard.press("ControlOrMeta+S")New property httpCredentials.send in api_request.new_context() that allows to either always send the Authorization header or only send it in response to 401 Unauthorized.
Playwright now supports Chromium, Firefox and WebKit on Ubuntu 24.04.
v1.45 is the last release to receive WebKit update for macOS 12 Monterey. Please update macOS to keep using the latest WebKit.
This version was also tested against the following stable channels:
Accessibility assertions
locator_assertions.to_have_accessible_name() checks if the element has the specified accessible name:
locator = page.get_by_role("button")
expect(locator).to_have_accessible_name("Submit")locator_assertions.to_have_accessible_description() checks if the element has the specified accessible description:
locator = page.get_by_role("button")
expect(locator).to_have_accessible_description("Upload a photo")locator_assertions.to_have_role() checks if the element has the specified ARIA role:
locator = page.get_by_test_id("save-button")
expect(locator).to_have_role("button")Locator handler
page.add_locator_handler(), Playwright will now wait until the overlay that triggered the handler is not visible anymore. You can opt-out of this behavior with the new no_wait_after option.times option in page.add_locator_handler() to specify maximum number of times the handler should be run.page.add_locator_handler() now accepts the locator as argument.page.remove_locator_handler() method for removing previously added locator handlers.locator = page.get_by_text("This interstitial covers the button")
page.add_locator_handler(locator, lambda overlay: overlay.locator("#close").click(), times=3, no_wait_after=True)
# Run your tests that can be interrupted by the overlay.
# ...
page.remove_locator_handler(locator)Miscellaneous options
page_assertions.to_have_url() now supports ignore_case option.This version was also tested against the following stable channels:
Method browser_context.clear_cookies() now supports filters to remove only some cookies.
# Clear all cookies.
context.clear_cookies()
# New: clear cookies with a particular name.
context.clear_cookies(name="session-id")
# New: clear cookies for a particular domain.
context.clear_cookies(domain="my-origin.com")New method locator.content_frame() converts a Locator object to a FrameLocator. This can be useful when you have a Locator object obtained somewhere, and later on would like to interact with the content inside the frame.
locator = page.locator("iframe[name='embedded']")
# ...
frame_locator = locator.content_frame
frame_locator.get_by_role("button").click()New method frame_locator.owner() converts a FrameLocator object to a Locator. This can be useful when you have a FrameLocator object obtained somewhere, and later on would like to interact with the iframe element.
frame_locator = page.frame_locator("iframe[name='embedded']")
# ...
locator = frame_locator.owner
expect(locator).to_be_visible()Conda builds are now published for macOS-arm64 and Linux-arm64.
This version was also tested against the following stable channels:
New method page.add_locator_handler() registers a callback that will be invoked when specified element becomes visible and may block Playwright actions. The callback can get rid of the overlay. Here is an example that closes a cookie dialog when it appears.
# Setup the handler.
page.add_locator_handler(
page.get_by_role("heading", name="Hej! You are in control of your cookies."),
lambda: page.get_by_role("button", name="Accept all").click(),
)
# Write the test as usual.
page.goto("https://www.ikea.com/")
page.get_by_role("link", name="Collection of blue and white").click()
expect(page.get_by_role("heading", name="Light and easy")).to_be_visible()page.pdf() accepts two new options tagged and outline.This version was also tested against the following stable channels:
page.unroute_all() removes all routes registered by page.route() and page.route_from_har(). Optionally allows to wait for ongoing routes to finish, or ignore any errors from them.browser_context.unroute_all() removes all routes registered by browser_context.route() and browser_context.route_from_har(). Optionally allows to wait for ongoing routes to finish, or ignore any errors from them.style in page.screenshot() and style in locator.screenshot() to add custom CSS to the page before taking a screenshot.This version was also tested against the following stable channels:
New tools to generate assertions:
locator_assertions.to_be_visible().locator_assertions.to_have_value().locator_assertions.to_contain_text().Here is an example of a generated test with assertions:
from playwright.sync_api import Page, expect
def test_example(page: Page) -> None:
page.goto("https://playwright.dev/")
page.get_by_role("link", name="Get started").click()
expect(page.get_by_label("Breadcrumbs").get_by_role("list")).to_contain_text("Installation")
expect(page.get_by_label("Search")).to_be_visible()
page.get_by_label("Search").click()
page.get_by_placeholder("Search docs").fill("locator")
expect(page.get_by_placeholder("Search docs")).to_have_value("locator");reason in page.close(), reason in browser_context.close() and reason in browser.close(). Close reason is reported for all operations interrupted by the closure.firefox_user_prefs in browser_type.launch_persistent_context().download.path() throws an error for failed and cancelled downloads.This version was also tested against the following stable channels:
Evergreen browsers update.
This version was also tested against the following stable channels:
page.type(), frame.type(), locator.type() and element_handle.type(). Please use locator.fill() instead which is much faster. Use locator.press_sequentially() only if there is a special keyboard handling on the page, and you need to press keys one-by-one.This version was also tested against the following stable channels:
pytest-playwright is now also getting published on AnacondaPlaywright now supports Debian 12 Bookworm on both x86_64 and arm64 for Chromium, Firefox and WebKit. Let us know if you encounter any issues!
Linux support looks like this:
| Ubuntu 20.04 | Ubuntu 22.04 | Debian 11 | Debian 12 | |
|---|---|---|---|---|
| Chromium | ✅ | ✅ | ✅ | ✅ |
| WebKit | ✅ | ✅ | ✅ | ✅ |
| Firefox | ✅ | ✅ | ✅ | ✅ |
This version was also tested against the following stable channels:
🏝️ Summer maintenance release.
This version was also tested against the following stable channels:
New option mask_color for methods page.screenshot() and locator.screenshot() to change default masking color.
New uninstall CLI command to uninstall browser binaries:
$ playwright uninstall # remove browsers installed by this installation
$ playwright uninstall --all # remove all ever-install Playwright browsersThis version was also tested against the following stable channels:
New locator.and_() to create a locator that matches both locators.
button = page.get_by_role("button").and_(page.get_by_title("Subscribe"))New events browserContext.on("console") and browserContext.on("dialog") to subscribe to any dialogs and console messages from any page from the given browser context. Use the new methods console_message.page() and dialog.page() to pin-point event source.
This version was also tested against the following stable channels:
Use locator.or_() to create a locator that matches either of the two locators. Consider a scenario where you'd like to click on a "New email" button, but sometimes a security settings dialog shows up instead. In this case, you can wait for either a "New email" button, or a dialog and act accordingly:
new_email = page.get_by_role("button", name="New email")
dialog = page.get_by_text("Confirm security settings")
expect(new_email.or_(dialog)).is_visible()
if (dialog.is_visible()):
page.get_by_role("button", name="Dismiss").click()
new_email.click()Use new options has_not and has_not_text in locator.filter() to find elements that do not match certain conditions.
row_locator = page.locator("tr")
row_locator.filter(has_not_text="text in column 1").filter(
has_not=page.get_by_role("button", name="column 2 button")
).screenshot()Use new web-first assertion locator_assertions.to_be_attached() to ensure that the element is present in the page's DOM. Do not confuse with the locator_assertions.to_be_visible() that ensures that element is both attached & visible.
locator.or_()has_not in locator.filter()has_not_text in locator.filter()locator_assertions.to_be_attached()timeout in route.fetch()mcr.microsoft.com/playwright/python:v1.33.0 now serves a Playwright image based on Ubuntu Jammy. To use the focal-based image, please use mcr.microsoft.com/playwright/python:v1.33.0-focal instead.This version was also tested against the following stable channels:
update_mode and update_content in page.route_from_har() and browser_context.route_from_har().name in method tracing.start_chunk().This version was also tested against the following stable channels:
New assertion locator_assertions.to_be_in_viewport() ensures that locator points to an element that intersects viewport, according to the intersection observer API.
from playwright.sync_api import expect
locator = page.get_by_role("button")
# Make sure at least some part of element intersects viewport.
expect(locator).to_be_in_viewport()
# Make sure element is fully outside of viewport.
expect(locator).not_to_be_in_viewport()
# Make sure that at least half of the element intersects viewport.
expect(locator).to_be_in_viewport(ratio=0.5)max_redirects for method route.fetch().This version was also tested against the following stable channels:
This version was also tested against the following stable channels:
New method route.fetch() and new option json for route.fulfill():
def handle_route(route: Route):
# Fetch original settings.
response = route.fetch()
# Force settings theme to a predefined value.
json = response.json()
json["theme"] = "Solorized"
# Fulfill with modified data.
route.fulfill(json=json)
page.route("**/api/settings", handle_route)New method locator.all() to iterate over all matching elements:
# Check all checkboxes!
checkboxes = page.get_by_role("checkbox")
for checkbox in checkboxes.all():
checkbox.check()locator.select_option() matches now by value or label:
<select multiple>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>element.select_option("Red")postData in method route.continue_() now supports [Serializable] values.This version was also tested against the following stable channels:

This version was also tested against the following stable channels:
With these new APIs writing locators is a joy:
page.get_by_text() to locate by text content.page.get_by_role() to locate by ARIA role, ARIA attributes and accessible name.page.get_by_label() to locate a form control by associated label's text.page.get_by_test_id() to locate an element based on its data-testid attribute (other attribute can be configured).page.get_by_placeholder() to locate an input by placeholder.page.get_by_alt_text() to locate an element, usually image, by its text alternative.page.get_by_title() to locate an element by its title.page.get_by_label("User Name").fill("John")
page.get_by_label("Password").fill("secret-password")
page.get_by_role("button", name="Sign in").click()
expect(page.get_by_text("Welcome, John!")).to_be_visible()All the same methods are also available on Locator, FrameLocator and Frame classes.
locator_assertions.to_have_attribute() with an empty value does not match missing attribute anymore. For example, the following snippet will succeed when button does not have a disabled attribute.
expect(page.get_by_role("button")).to_have_attribute("disabled", "")This version was also tested against the following stable channels:
enabled for locator_assertions.to_be_enabled().locator_assertions.to_have_text() now pierces open shadow roots.editable for locator_assertions.to_be_editable().visible for locator_assertions.to_be_visible().max_redirects for api_request_context.get() and others to limit redirect count.A bunch of Playwright APIs already support the wait_until: "domcontentloaded" option. For example:
page.goto("https://playwright.dev", wait_until="domcontentloaded")Prior to 1.26, this would wait for all iframes to fire the DOMContentLoaded event.
To align with web specification, the 'domcontentloaded' value only waits for the target frame to fire the 'DOMContentLoaded' event. Use wait_until="load" to wait for all iframes.
This version was also tested against the following stable channels:
mcr.microsoft.com/playwright/python:v1.34.0-jammy.This version was also tested against the following stable channels:
Playwright now supports Debian 11 Bullseye on x86_64 for Chromium, Firefox and WebKit. Let us know if you encounter any issues!
Linux support looks like this:
| | Ubuntu 20.04 | Ubuntu 22.04 | Debian 11 | :--- | :---: | :---: | :---: | :---: | | Chromium | ✅ | ✅ | ✅ | | WebKit | ✅ | ✅ | ✅ | | Firefox | ✅ | ✅ | ✅ |
We rewrote our Getting Started docs to be more end-to-end testing focused. Check them out on playwright.dev.
Now you can record network traffic into a HAR file and re-use this traffic in your tests.
To record network into HAR file:
npx playwright open --save-har=github.har.zip https://github.com/microsoftAlternatively, you can record HAR programmatically:
context = await browser.new_context(record_har_path="github.har.zip")
# ... do stuff ...
await context.close()context = browser.new_context(record_har_path="github.har.zip")
# ... do stuff ...
context.close()Use the new methods page.route_from_har() or browser_context.route_from_har() to serve matching responses from the HAR file:
await context.route_from_har("github.har.zip")context.route_from_har("github.har.zip")Read more in our documentation.
You can now use route.fallback() to defer routing to other handlers.
Consider the following example:
# Remove a header from all requests
async def remove_header_handler(route: Route) -> None:
headers = await route.request.all_headers()
if "if-none-match" in headers:
del headers["if-none-match"]
await route.fallback(headers=headers)
await page.route("**/*", remove_header_handler)
# Abort all images
async def abort_images_handler(route: Route) -> None:
if route.request.resource_type == "image":
await route.abort()
else:
await route.fallback()
await page.route("**/*", abort_images_handler)# Remove a header from all requests
def remove_header_handler(route: Route) -> None:
headers = route.request.all_headers()
if "if-none-match" in headers:
del headers["if-none-match"]
route.fallback(headers=headers)
page.route("**/*", remove_header_handler)
# Abort all images
def abort_images_handler(route: Route) -> None:
if route.request.resource_type == "image":
route.abort()
else:
route.fallback()
page.route("**/*", abort_images_handler)Note that the new methods page.route_from_har() and browser_context.route_from_har() also participate in routing and could be deferred to.
locator_assertions.to_have_values() that asserts all selected values of <select multiple> element.locator_assertions.to_contain_text() and locator_assertions.to_have_text() now accept ignore_case option.If there's a service worker that's in your way, you can now easily disable it with a new context option service_workers:
context = await browser.new_context(service_workers="block")
page = await context.new_page()context = browser.new_context(service_workers="block")
page = context.new_page()Using .zip path for recordHar context option automatically zips the resulting HAR:
context = await browser.new_context(record_har_path="github.har.zip")context = browser.new_context(record_har_path="github.har.zip")If you intend to edit HAR by hand, consider using the "minimal" HAR recording mode that only records information that is essential for replaying:
context = await browser.new_context(record_har_mode="minimal", record_har_path="har.har")context = browser.new_context(record_har_mode="minimal", record_har_path="har.har")Playwright now runs on Ubuntu 22 amd64 and Ubuntu 22 arm64.
Role selectors that allow selecting elements by their ARIA role, ARIA attributes and accessible name.
# Click a button with accessible name "log in"
page.locator("role=button[name='log in']").click()Read more in our documentation.
New locator.filter() API to filter an existing locator
buttons = page.locator("role=button")
# ...
submit_button = buttons.filter(has_text="Submit")
submit_button.click()Codegen now supports generating Pytest Tests

New role selectors that allow selecting elements by their ARIA role, ARIA attributes and accessible name.
# Click a button with accessible name "log in"
await page.locator("role=button[name='log in']").click()# Click a button with accessible name "log in"
page.locator("role=button[name='log in']").click()Read more in our documentation.
New scale option in page.screenshot() for smaller sized screenshots.
New caret option in page.screenshot() to control text caret. Defaults to "hide".
mcr.microsoft.com/playwright docker image no longer contains Python. Please use mcr.microsoft.com/playwright/python as a Playwright-ready docker image with pre-installed Python.locator.set_input_files() API.This version was also tested against the following stable channels:
page.screenshot(), locator.screenshot() and element_handle.screenshot(): animations: "disabled" rewinds all CSS animations and transitions to a consistent statemask: Locator[] masks given elements, overlaying them with pink #FF00FF boxes.locator.highlight() visually reveals element(s) for easier debugging.mcr.microsoft.com/playwright/python. Please switch over to it if you use Python. This is the last release that includes Python inside our javascript mcr.microsoft.com/playwright docker image.This version was also tested against the following stable channels:
Locator now supports a has option that makes sure it contains another locator inside:
await page.locator("article", has=page.locator(".highlight")).click()page.locator("article", has=page.locator(".highlight")).click()Read more in locator documentation
New locator.page()
page.screenshot() and locator.screenshot() now automatically hide blinking caret
Playwright Codegen now generates locators and frame locators
This version was also tested against the following stable channels:
Playwright for Python 1.18 introduces new API Testing that lets you send requests to the server directly from Python! Now you can:
To do a request on behalf of Playwright's Page, use new page.request API:
# Do a GET request on behalf of page
res = await page.request.get("http://example.com/foo.json")# Do a GET request on behalf of page
res = page.request.get("http://example.com/foo.json")Read more in our documentation.
Playwright for Python 1.18 introduces Web-First Assertions.
Consider the following example:
from playwright.async_api import Page, expect
async def test_status_becomes_submitted(page: Page) -> None:
# ..
await page.locator("#submit-button").click()
await expect(page.locator(".status")).to_have_text("Submitted")from playwright.sync_api import Page, expect
def test_status_becomes_submitted(page: Page) -> None:
# ..
page.locator("#submit-button").click()
expect(page.locator(".status")).to_have_text("Submitted")Playwright will be re-testing the node with the selector .status until fetched Node has the "Submitted" text. It will be re-fetching the node and checking it over and over, until the condition is met or until the timeout is reached. You can pass this timeout as an option.
Read more in our documentation.
Each locator can now be optionally filtered by the text it contains:
await page.locator("li", has_text="my item").locator("button").click()page.locator("li", has_text="my item").locator("button").click()Read more in locator documentation
accept_downloads option now defaults to True.sources option to embed sources into traces.This version was also tested against the following stable channels:
Playwright 1.17 introduces frame locators - a locator to the iframe on the page. Frame locators capture the logic sufficient to retrieve the iframe and then locate elements in that iframe. Frame locators are strict by default, will wait for iframe to appear and can be used in Web-First assertions.

Frame locators can be created with either page.frame_locator() or locator.frame_locator() method.
locator = page.frame_locator("my-frame").locator("text=Submit")
locator.click()Read more at our documentation.
Playwright Trace Viewer is now available online at https://trace.playwright.dev! Just drag-and-drop your trace.zip file to inspect its contents.
NOTE: trace files are not uploaded anywhere; trace.playwright.dev is a progressive web application that processes traces locally.


Playwright now supports Ubuntu 20.04 ARM64. You can now run Playwright tests inside Docker on Apple M1 and on Raspberry Pi.
You can now use Playwright to install stable version of Edge on Linux:
npx playwright install msedgelocator.wait_for Wait for a locator to resolve to a single element with a given state. Defaults to the state: 'visible'.
Comes especially handy when working with lists:
order_sent = page.locator("#order-sent")
order_sent.wait_for()Read more about locator.wait_for().
Playwright Docker image is now published for Arm64 so it can be used on Apple Silicon.
Read more about Docker integration.
npx playwright show-trace and drop trace files to the trace viewer PWARead more about Trace Viewer.
This version of Playwright was also tested against the following stable channels:
By using mouse.wheel() you are now able to scroll vertically or horizontally.
Previously it was not possible to get multiple header values of a response. This is now possible and additional helper functions are available:
request.all_headers()request.headers_array()request.header_value()response.all_headers()response.headers_array()response.header_value()response.header_values()Its now possible to emulate the forced-colors CSS media feature by passing it in the browser.new_context() or calling page.emulate_media().
page.route() accepts new times option to specify how many times this route should be matched.page.set_checked() and locator.set_checked() were introduced to set the checked state of a checkbox.request.sizes() Returns resource size information for given http request.tracing.start_chunk() - Start a new trace chunk.tracing.stop_chunk() - Stops a new trace chunk.Selector ambiguity is a common problem in automation testing. "strict" mode ensures that your selector points to a single element and throws otherwise.
Pass strict=true into your action calls to opt in.
# This will throw if you have more than one button!
page.click("button", strict=True)Locator represents a view to the element(s) on the page. It captures the logic sufficient to retrieve the element at any given moment.
The difference between the Locator and ElementHandle is that the latter points to a particular element, while Locator captures the logic of how to retrieve that element.
Also, locators are "strict" by default!
locator = page.locator("button")
locator.click()Learn more in the documentation.
React and Vue selectors allow selecting elements by its component name and/or property values. The syntax is very similar to attribute selectors and supports all attribute selector operators.
page.locator("_react=SubmitButton[enabled=true]").click()
page.locator("_vue=submit-button[enabled=true]").click()Learn more in the react selectors documentation and the vue selectors documentation.
nth and visible selector engines nth selector engine is equivalent to the :nth-match pseudo class, but could be combined with other selector engines.visible selector engine is equivalent to the :visible pseudo class, but could be combined with other selector engines.# select the first button among all buttons
button.click("button >> nth=0")
# or if you are using locators, you can use first, nth() and last
page.locator("button").first.click()
# click a visible button
button.click("button >> visible=true")page.drag_and_drop() API.recordHar option in browser.new_context().console.log() calls.baseURL option in browser.new_context() and browser.new_page()response.security_details() and response.server_addr()page.drag_and_drop() and frame.drag_and_drop()download.cancel()page.input_value(), frame.input_value() and element_handle.input_value()force option in page.fill(), frame.fill(), and element_handle.fill()force option in page.select_option(), frame.select_option(), and element_handle.select_option()Playwright Trace Viewer is a new GUI tool that helps exploring recorded Playwright traces after the script ran. Playwright traces let you examine:
Traces are recorded using the new browser_context.tracing API:
browser = chromium.launch()
context = browser.new_context()
# Start tracing before creating / navigating a page.
context.tracing.start(screenshots=True, snapshots=True)
page.goto("https://playwright.dev")
# Stop tracing and export it into a zip archive.
context.tracing.stop(path = "trace.zip")Traces are examined later with the Playwright CLI:
playwright show-trace trace.zipThat will open the following GUI:

👉 Read more in trace viewer documentation.
This version of Playwright was also tested against the following stable channels:
reducedMotion option in page.emulate_media(), browser_type.launch_persistent_context(), browser.new_context() and browser.new_page()browserContext.on("request")browserContext.on("requestFailed")browserContext.on("requestFinished")browserContext.on("response")tracesDir option in browser_type.launch() and browser_type.launch_persistent_context()browser_context.tracing API namespacedownload.page() method🎥 New video: Playwright: A New Test Automation Framework for the Modern Web (slides)
page.expect_request() and otherspage.wait_for_url() to await navigations to URLvideo.delete() and video.save_as() to manage screen recordingscreen option in the browser.new_context() method to emulate window.screen dimensionsposition option in page.check() and page.uncheck() methodstrial option to dry-run actions in page.check(), page.uncheck(), page.click(), page.dblclick(), page.hover() and page.tap()This version of Playwright was also tested against the following stable channels:
browser_type.launch() now accepts the new 'channel' option. Read more in our documentation.PWDEBUG=1 environment variable to launch the Inspectorpage.pause() in headed mode. Pausing the page launches Playwright Inspector for debugging.:has-text("example") matches any element containing "example" somewhere inside, possibly in a child or a descendant element. See more examples.dialog event is configured. Learn more about this.Selecting elements based on layout with :left-of(), :right-of(), :above() and :below().
Playwright now includes command line interface, former playwright-cli.
playwright --helppage.select_option() now waits for the options to be present.
New methods to assert element state like page.is_editable().
element_handle.is_checked().element_handle.is_disabled().element_handle.is_editable().element_handle.is_enabled().element_handle.is_hidden().element_handle.is_visible().page.is_checked().page.is_disabled().page.is_editable().page.is_enabled().page.is_hidden().page.is_visible().'editable' in element_handle.wait_for_element_state().browser_context.storage_state() to get current state for later reuse.storageState option in browser.new_context() and browser.new_page() to setup browser context state.