Page
Page provides methods to interact with a single tab in a Browser, or an extension background page in Chromium. One Browser instance might have multiple Page instances.
This example creates a page, navigates it to a URL, and then saves a screenshot:
- Sync
- Async
from playwright.sync_api import sync_playwright, Playwright
def run(playwright: Playwright):
webkit = playwright.webkit
browser = webkit.launch()
context = browser.new_context()
page = context.new_page()
page.goto("https://example.com")
page.screenshot(path="screenshot.png")
browser.close()
with sync_playwright() as playwright:
run(playwright)
import asyncio
from playwright.async_api import async_playwright, Playwright
async def run(playwright: Playwright):
webkit = playwright.webkit
browser = await webkit.launch()
context = await browser.new_context()
page = await context.new_page()
await page.goto("https://example.com")
await page.screenshot(path="screenshot.png")
await browser.close()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
The Page class emits various events (described below) which can be handled using any of Node's native EventEmitter methods, such as on, once or removeListener.
This example logs a message for a single page load event:
page.once("load", lambda: print("page loaded!"))
To unsubscribe from events use the removeListener method:
def log_request(intercepted_request):
print("a request was made:", intercepted_request.url)
page.on("request", log_request)
# sometime later...
page.remove_listener("request", log_request)
Methods
add_init_script
Added before v1.9Adds a script which would be evaluated in one of the following scenarios:
- Whenever the page is navigated.
- Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame.
The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.
Usage
An example of overriding Math.random before the page loads:
// preload.js
Math.random = () => 42;
- Sync
- Async
# in your playwright script, assuming the preload.js file is in same directory
page.add_init_script(path="./preload.js")
# in your playwright script, assuming the preload.js file is in same directory
await page.add_init_script(path="./preload.js")
The order of evaluation of multiple scripts installed via browser_context.add_init_script() and page.add_init_script() is not defined.
Arguments
-
pathUnion[str, pathlib.Path] (optional)#Path to the JavaScript file. If
pathis a relative path, then it is resolved relative to the current working directory. Optional. -
Script to be evaluated in all pages in the browser context. Optional.
Returns
add_locator_handler
Added in: v1.42When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making them tricky to handle in automated tests.
This method lets you set up a special function, called a handler, that activates when it detects that overlay is visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.
Things to keep in mind:
- When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as a part of your normal test flow, instead of using page.add_locator_handler().
- Playwright checks for the overlay every time before executing or retrying an action that requires an actionability check, or before performing an auto-waiting assertion check. When overlay is visible, Playwright calls the handler first, and then proceeds with the action/assertion. Note that the handler is only called when you perform an action/assertion - if the overlay becomes visible but you don't perform any actions, the handler will not be triggered.
- After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible anymore. You can opt-out of this behavior with no_wait_after.
- The execution time of the handler counts towards the timeout of the action/assertion that executed the handler. If your handler takes too long, it might cause timeouts.
- You can register multiple handlers. However, only a single handler will be running at a time. Make sure the actions within a handler don't depend on another handler.
Running the handler will alter your page state mid-test. For example it will change the currently focused element and move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on the focus and mouse state being unchanged.
For example, consider a test that calls locator.focus() followed by keyboard.press(). If your handler clicks a button between these two actions, the focused element most likely will be wrong, and key press will happen on the unexpected element. Use locator.press() instead to avoid this problem.
Another example is a series of mouse actions, where mouse.move() is followed by mouse.down(). Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse down. Prefer self-contained actions like locator.click() that do not rely on the state being unchanged by a handler.
Usage
An example that closes a "Sign up to the newsletter" dialog when it appears:
- Sync
- Async
# Setup the handler.
def handler():
page.get_by_role("button", name="No thanks").click()
page.add_locator_handler(page.get_by_text("Sign up to the newsletter"), handler)
# Write the test as usual.
page.goto("https://example.com")
page.get_by_role("button", name="Start here").click()
# Setup the handler.
async def handler():
await page.get_by_role("button", name="No thanks").click()
await page.add_locator_handler(page.get_by_text("Sign up to the newsletter"), handler)
# Write the test as usual.
await page.goto("https://example.com")
await page.get_by_role("button", name="Start here").click()
An example that skips the "Confirm your security details" page when it is shown:
- Sync
- Async
# Setup the handler.
def handler():
page.get_by_role("button", name="Remind me later").click()
page.add_locator_handler(page.get_by_text("Confirm your security details"), handler)
# Write the test as usual.
page.goto("https://example.com")
page.get_by_role("button", name="Start here").click()
# Setup the handler.
async def handler():
await page.get_by_role("button", name="Remind me later").click()
await page.add_locator_handler(page.get_by_text("Confirm your security details"), handler)
# Write the test as usual.
await page.goto("https://example.com")
await page.get_by_role("button", name="Start here").click()
An example with a custom callback on every actionability check. It uses a <body> locator that is always visible, so the handler is called before every actionability check. It is important to specify no_wait_after, because the handler does not hide the <body> element.
- Sync
- Async
# Setup the handler.
def handler():
page.evaluate("window.removeObstructionsForTestIfNeeded()")
page.add_locator_handler(page.locator("body"), handler, no_wait_after=True)
# Write the test as usual.
page.goto("https://example.com")
page.get_by_role("button", name="Start here").click()
# Setup the handler.
async def handler():
await page.evaluate("window.removeObstructionsForTestIfNeeded()")
await page.add_locator_handler(page.locator("body"), handler, no_wait_after=True)
# Write the test as usual.
await page.goto("https://example.com")
await page.get_by_role("button", name="Start here").click()
Handler takes the original locator as an argument. You can also automatically remove the handler after a number of invocations by setting times:
- Sync
- Async
def handler(locator):
locator.click()
page.add_locator_handler(page.get_by_label("Close"), handler, times=1)
async def handler(locator):
await locator.click()
await page.add_locator_handler(page.get_by_label("Close"), handler, times=1)
Arguments
-
Locator that triggers the handler.
-
handlerCallable[Locator] | Callable[]:Promise[Any]#Function that should be run once locator appears. This function should get rid of the element that blocks actions like click.
-
no_wait_afterbool (optional) Added in: v1.44#By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then Playwright will continue with the action/assertion that triggered the handler. This option allows to opt-out of this behavior, so that overlay can stay visible after the handler has run.
-
timesint (optional) Added in: v1.44#Specifies the maximum number of times this handler should be called. Unlimited by default.
Returns
add_script_tag
Added before v1.9Adds a <script> tag into the page with the desired url or content. Returns the added tag when the script's onload fires or when the script content was injected into frame.
Usage
page.add_script_tag()
page.add_script_tag(**kwargs)
Arguments
-
Raw JavaScript content to be injected into frame.
-
pathUnion[str, pathlib.Path] (optional)#Path to the JavaScript file to be injected into frame. If
pathis a relative path, then it is resolved relative to the current working directory. -
Script type. Use 'module' in order to load a JavaScript ES6 module. See script for more details.
-
URL of a script to be added.
Returns
add_style_tag
Added before v1.9Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
Usage
page.add_style_tag()
page.add_style_tag(**kwargs)
Arguments
-
Raw CSS content to be injected into frame.
-
pathUnion[str, pathlib.Path] (optional)#Path to the CSS file to be injected into frame. If
pathis a relative path, then it is resolved relative to the current working directory. -
URL of the
<link>tag.
Returns
aria_snapshot
Added in: v1.59Captures the aria snapshot of the page. Read more about aria snapshots.
Usage
page.aria_snapshot()
page.aria_snapshot(**kwargs)
Arguments
-
boxesbool (optional) Added in: v1.60#When
true, appends each element's bounding box as[box=x,y,width,height]to the snapshot. Coordinates are relative to the viewport, in CSS pixels, as returned byElement.getBoundingClientRect(). Defaults tofalse. -
When specified, limits the depth of the snapshot.
-
mode"ai" | "default" (optional)#When set to
"ai", returns a snapshot optimized for AI consumption: including element references like[ref=e2]and snapshots of<iframe>s. Defaults to"default". -
Maximum time in milliseconds. Defaults to
30000(30 seconds). Pass0to disable timeout. The default value can be changed by using the browser_context.set_default_timeout() or page.set_default_timeout() methods.
Returns
bring_to_front
Added before v1.9Brings page to front (activates tab).
Usage
page.bring_to_front()
Returns
cancel_pick_locator
Added in: v1.59Cancels an ongoing page.pick_locator() call by deactivating pick locator mode. If no pick locator mode is active, this method is a no-op.
Usage
page.cancel_pick_locator()
Returns
clear_console_messages
Added in: v1.59Clears all stored console messages from this page. Subsequent calls to page.console_messages() will only return messages logged after the clear.
Usage
page.clear_console_messages()
Returns
clear_page_errors
Added in: v1.59Clears all stored page errors from this page. Subsequent calls to page.page_errors() will only return errors thrown after the clear.
Usage
page.clear_page_errors()
Returns
close
Added before v1.9If run_before_unload is false, does not run any unload handlers and waits for the page to be closed. If run_before_unload is true the method will run unload handlers, but will not wait for the page to close.
By default, page.close() does not run beforeunload handlers.
if run_before_unload is passed as true, a beforeunload dialog might be summoned and should be handled manually via page.on("dialog") event.
Usage
page.close()
page.close(**kwargs)
Arguments
-
reasonstr (optional) Added in: v1.40#The reason to be reported to the operations interrupted by the page closure.
-
run_before_unloadbool (optional)#Defaults to
false. Whether to run the before unload page handlers.
Returns
console_messages
Added in: v1.56Returns up to (currently) 200 last console messages from this page. See page.on("console") for more details.
Usage
page.console_messages()
page.console_messages(**kwargs)
Arguments
-
filter"all" | "since-navigation" (optional) Added in: v1.59#Controls which messages are returned:
Returns
content
Added before v1.9Gets the full HTML contents of the page, including the doctype.
Usage
page.content()
page.content(**kwargs)
Arguments
-
include_shadowbool (optional) Added in: v1.64#When true, contents of open shadow roots are included as declarative shadow DOM, i.e.
<template shadowrootmode="open">elements nested inside their host elements. Closed shadow roots are never included. Defaults tofalse.
Returns
drag_and_drop
Added in: v1.13This method drags the source element to the target element. It will first move to the source element, perform a mousedown, then move to the target element and perform a mouseup.
Usage
- Sync
- Async
page.drag_and_drop("#source", "#target")
# or specify exact positions relative to the top-left corners of the elements:
page.drag_and_drop(
"#source",
"#target",
source_position={"x": 34, "y": 7},
target_position={"x": 10, "y": 20}
)
await page.drag_and_drop("#source", "#target")
# or specify exact positions relative to the top-left corners of the elements:
await page.drag_and_drop(
"#source",
"#target",
source_position={"x": 34, "y": 7},
target_position={"x": 10, "y": 20}
)
Arguments
-
A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.
-
A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used.
-
Whether to bypass the actionability checks. Defaults to
false. -
no_wait_afterbool (optional)#DeprecatedThis option has no effect.
This option has no effect.
-
scroll"auto" | "none" (optional) Added in: v1.62#Controls whether Playwright scrolls the element into view before performing the action. Defaults to
"auto", which scrolls the element into view when necessary, including scrolling nested scrollable containers. When set to"none", Playwright does not scroll the element and the action fails if the element is not already in the viewport. This is useful to assert that an element is reachable by the user without additional scrolling. -
source_positionDict (optional) Added in: v1.14#Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not specified, some visible point of the element is used.
-
stepsint (optional) Added in: v1.57#Defaults to 1. Sends
ninterpolatedmousemoveevents to represent travel between themousedownandmouseupof the drag. When set to 1, emits a singlemousemoveevent at the destination location. -
strictbool (optional) Added in: v1.14#When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
-
target_positionDict (optional) Added in: v1.14#-
x
-