class Playwright::Page
-
extends: [EventEmitter]
Page
provides methods to interact with a single tab in a `Browser`, or an [extension background page](developer.chrome.com/extensions/background_pages) 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:
“`python sync from playwright.sync_api import sync_playwright
def run(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)
“`
The Page
class emits various events (described below) which can be handled using any of Node's native [`EventEmitter`](nodejs.org/api/events.html#events_class_eventemitter) methods, such as `on`, `once` or `removeListener`.
This example logs a message for a single page `load` event:
“`py page.once(“load”, lambda: print(“page loaded!”)) “`
To unsubscribe from events use the `removeListener` method:
“`py 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) “`
Public Instance Methods
# File lib/playwright_api/page.rb, line 47 def accessibility # property wrap_impl(@impl.accessibility) end
Adds 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`.
An example of overriding `Math.random` before the page loads:
“`python sync # in your playwright script, assuming the preload.js file is in same directory page.add_init_script(path=“./preload.js”) “`
> NOTE: The order of evaluation of multiple scripts installed via [`method: BrowserContext.addInitScript`] and
- `method: Page.addInitScript`
-
is not defined.
# File lib/playwright_api/page.rb, line 80 def add_init_script(path: nil, script: nil) wrap_impl(@impl.add_init_script(path: unwrap_impl(path), script: unwrap_impl(script))) end
Adds 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.
Shortcut for main frame's [`method: Frame.addScriptTag`].
# File lib/playwright_api/page.rb, line 88 def add_script_tag(content: nil, path: nil, type: nil, url: nil) wrap_impl(@impl.add_script_tag(content: unwrap_impl(content), path: unwrap_impl(path), type: unwrap_impl(type), url: unwrap_impl(url))) end
Adds 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.
Shortcut for main frame's [`method: Frame.addStyleTag`].
# File lib/playwright_api/page.rb, line 96 def add_style_tag(content: nil, path: nil, url: nil) wrap_impl(@impl.add_style_tag(content: unwrap_impl(content), path: unwrap_impl(path), url: unwrap_impl(url))) end
Brings page to front (activates tab).
# File lib/playwright_api/page.rb, line 101 def bring_to_front wrap_impl(@impl.bring_to_front) end
This method checks an element matching `selector` by performing the following steps:
-
Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
-
Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already checked, this method returns immediately.
-
Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
-
Scroll the element into view if needed.
-
Use [`property:
Page.mouse
`] to click in the center of the element. -
Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
-
Ensure that the element is now checked. If not, this method throws.
When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`. Passing zero timeout disables this.
Shortcut for main frame's [`method: Frame.check
`].
# File lib/playwright_api/page.rb, line 120 def check( selector, force: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) wrap_impl(@impl.check(unwrap_impl(selector), force: unwrap_impl(force), noWaitAfter: unwrap_impl(noWaitAfter), position: unwrap_impl(position), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial))) end
Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
# File lib/playwright_api/page.rb, line 625 def checked?(selector, strict: nil, timeout: nil) wrap_impl(@impl.checked?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
This method clicks an element matching `selector` by performing the following steps:
-
Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
-
Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
-
Scroll the element into view if needed.
-
Use [`property:
Page.mouse
`] to click in the center of the element, or the specified `position`. -
Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`. Passing zero timeout disables this.
Shortcut for main frame's [`method: Frame.click
`].
# File lib/playwright_api/page.rb, line 143 def click( selector, button: nil, clickCount: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) wrap_impl(@impl.click(unwrap_impl(selector), button: unwrap_impl(button), clickCount: unwrap_impl(clickCount), delay: unwrap_impl(delay), force: unwrap_impl(force), modifiers: unwrap_impl(modifiers), noWaitAfter: unwrap_impl(noWaitAfter), position: unwrap_impl(position), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial))) end
If `runBeforeUnload` is `false`, does not run any unload handlers and waits for the page to be closed. If `runBeforeUnload` 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.
> NOTE: if `runBeforeUnload` is passed as true, a `beforeunload` dialog might be summoned and should be handled manually via [`event: Page.dialog`] event.
# File lib/playwright_api/page.rb, line 165 def close(runBeforeUnload: nil) wrap_impl(@impl.close(runBeforeUnload: unwrap_impl(runBeforeUnload))) end
Indicates that the page has been closed.
# File lib/playwright_api/page.rb, line 630 def closed? wrap_impl(@impl.closed?) end
Gets the full HTML contents of the page, including the doctype.
# File lib/playwright_api/page.rb, line 170 def content wrap_impl(@impl.content) end
Get the browser context that the page belongs to.
# File lib/playwright_api/page.rb, line 175 def context wrap_impl(@impl.context) end
This method double clicks an element matching `selector` by performing the following steps:
-
Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
-
Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
-
Scroll the element into view if needed.
-
Use [`property:
Page.mouse
`] to double click in the center of the element, or the specified `position`. -
Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set. Note that if the first click of the `dblclick()` triggers a navigation event, this method will throw.
When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`. Passing zero timeout disables this.
> NOTE: `page.dblclick()` dispatches two `click` events and a single `dblclick` event.
Shortcut for main frame's [`method: Frame.dblclick
`].
# File lib/playwright_api/page.rb, line 194 def dblclick( selector, button: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) wrap_impl(@impl.dblclick(unwrap_impl(selector), button: unwrap_impl(button), delay: unwrap_impl(delay), force: unwrap_impl(force), modifiers: unwrap_impl(modifiers), noWaitAfter: unwrap_impl(noWaitAfter), position: unwrap_impl(position), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial))) end
Returns whether the element is disabled, the opposite of [enabled](./actionability.md#enabled).
# File lib/playwright_api/page.rb, line 635 def disabled?(selector, strict: nil, timeout: nil) wrap_impl(@impl.disabled?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element, `click` is dispatched. This is equivalent to calling [element.click()](developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
“`python sync page.dispatch_event(“button#submit”, “click”) “`
Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit` properties and dispatches it on the element. Events
are `composed`, `cancelable` and bubble by default.
Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
-
[DragEvent](developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
-
[FocusEvent](developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
-
[KeyboardEvent](developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
-
[MouseEvent](developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
-
[PointerEvent](developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
-
[TouchEvent](developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
-
[Event](developer.mozilla.org/en-US/docs/Web/API/Event/Event)
You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
“`python sync # note you can only create data_transfer in chromium and firefox data_transfer = page.evaluate_handle(“new DataTransfer()”) page.dispatch_event(“#source”, “dragstart”, { “dataTransfer”: data_transfer }) “`
# File lib/playwright_api/page.rb, line 235 def dispatch_event( selector, type, eventInit: nil, strict: nil, timeout: nil) wrap_impl(@impl.dispatch_event(unwrap_impl(selector), unwrap_impl(type), eventInit: unwrap_impl(eventInit), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
# File lib/playwright_api/page.rb, line 244 def drag_and_drop( source, target, force: nil, noWaitAfter: nil, sourcePosition: nil, strict: nil, targetPosition: nil, timeout: nil, trial: nil) wrap_impl(@impl.drag_and_drop(unwrap_impl(source), unwrap_impl(target), force: unwrap_impl(force), noWaitAfter: unwrap_impl(noWaitAfter), sourcePosition: unwrap_impl(sourcePosition), strict: unwrap_impl(strict), targetPosition: unwrap_impl(targetPosition), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial))) end
Returns whether the element is [editable](./actionability.md#editable).
# File lib/playwright_api/page.rb, line 640 def editable?(selector, strict: nil, timeout: nil) wrap_impl(@impl.editable?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
This method changes the `CSS media type` through the `media` argument, and/or the `'prefers-colors-scheme'` media feature, using the `colorScheme` argument.
“`python sync page.evaluate(“matchMedia('screen').matches”) # → True page.evaluate(“matchMedia('print').matches”) # → False
page.emulate_media(media=“print”) page.evaluate(“matchMedia('screen').matches”) # → False page.evaluate(“matchMedia('print').matches”) # → True
page.emulate_media() page.evaluate(“matchMedia('screen').matches”) # → True page.evaluate(“matchMedia('print').matches”) # → False “`
“`python sync page.emulate_media(color_scheme=“dark”) page.evaluate(“matchMedia('(prefers-color-scheme: dark)').matches”) # → True page.evaluate(“matchMedia('(prefers-color-scheme: light)').matches”) # → False page.evaluate(“matchMedia('(prefers-color-scheme: no-preference)').matches”) “`
# File lib/playwright_api/page.rb, line 287 def emulate_media(colorScheme: nil, media: nil, reducedMotion: nil) wrap_impl(@impl.emulate_media(colorScheme: unwrap_impl(colorScheme), media: unwrap_impl(media), reducedMotion: unwrap_impl(reducedMotion))) end
Returns whether the element is [enabled](./actionability.md#enabled).
# File lib/playwright_api/page.rb, line 645 def enabled?(selector, strict: nil, timeout: nil) wrap_impl(@impl.enabled?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
The method finds an element matching the specified selector within the page and passes it as a first argument to `expression`. If no elements match the selector, the method throws an error. Returns the value of `expression`.
If `expression` returns a [Promise], then [`method: Page.evalOnSelector`] would wait for the promise to resolve and return its value.
Examples:
“`python sync search_value = page.eval_on_selector(“#search”, “el => el.value”) preload_href = page.eval_on_selector(“link”, “el => el.href”) html = page.eval_on_selector(“.main-container”, “(e, suffix) => e.outer_html + suffix”, “hello”) “`
Shortcut for main frame's [`method: Frame.evalOnSelector`].
# File lib/playwright_api/page.rb, line 306 def eval_on_selector(selector, expression, arg: nil, strict: nil) wrap_impl(@impl.eval_on_selector(unwrap_impl(selector), unwrap_impl(expression), arg: unwrap_impl(arg), strict: unwrap_impl(strict))) end
The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument to `expression`. Returns the result of `expression` invocation.
If `expression` returns a [Promise], then [`method: Page.evalOnSelectorAll`] would wait for the promise to resolve and return its value.
Examples:
“`python sync div_counts = page.eval_on_selector_all(“div”, “(divs, min) => divs.length >= min”, 10) “`
# File lib/playwright_api/page.rb, line 321 def eval_on_selector_all(selector, expression, arg: nil) wrap_impl(@impl.eval_on_selector_all(unwrap_impl(selector), unwrap_impl(expression), arg: unwrap_impl(arg))) end
Returns the value of the `expression` invocation.
If the function passed to the [`method: Page.evaluate
`] returns a [Promise], then [`method: Page.evaluate
`] would wait for the promise to resolve and return its value.
If the function passed to the [`method: Page.evaluate
`] returns a non- value, then
- `method:
Page.evaluate
` -
resolves to `undefined`.
Playwright
also supports transferring some additional values that are
not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
Passing argument to `expression`:
“`python sync result = page.evaluate(“([x, y]) => Promise.resolve(x * y)”, [7, 8]) print(result) # prints “56” “`
A string can also be passed in instead of a function:
“`python sync print(page.evaluate(“1 + 2”)) # prints “3” x = 10 print(page.evaluate(f“1 + {x}”)) # prints “11” “`
`ElementHandle` instances can be passed as an argument to the [`method: Page.evaluate
`]:
“`python sync body_handle = page.query_selector(“body”) html = page.evaluate(“([body, suffix]) => body.innerHTML + suffix”, [body_handle, “hello”]) body_handle.dispose() “`
Shortcut for main frame's [`method: Frame.evaluate
`].
# File lib/playwright_api/page.rb, line 358 def evaluate(expression, arg: nil) wrap_impl(@impl.evaluate(unwrap_impl(expression), arg: unwrap_impl(arg))) end
Returns the value of the `expression` invocation as a `JSHandle`.
The only difference between [`method: Page.evaluate
`] and [`method: Page.evaluateHandle`] is that
- `method: Page.evaluateHandle`
-
returns `JSHandle`.
If the function passed to the [`method: Page.evaluateHandle`] returns a [Promise], then [`method: Page.evaluateHandle`] would wait for the promise to resolve and return its value.
“`python sync a_window_handle = page.evaluate_handle(“Promise.resolve(window)”) a_window_handle # handle for the window object. “`
A string can also be passed in instead of a function:
“`python sync a_handle = page.evaluate_handle(“document”) # handle for the “document” “`
`JSHandle` instances can be passed as an argument to the [`method: Page.evaluateHandle`]:
“`python sync a_handle = page.evaluate_handle(“document.body”) result_handle = page.evaluate_handle(“body => body.innerHTML”, a_handle) print(result_handle.json_value()) result_handle.dispose() “`
# File lib/playwright_api/page.rb, line 389 def evaluate_handle(expression, arg: nil) wrap_impl(@impl.evaluate_handle(unwrap_impl(expression), arg: unwrap_impl(arg))) end
Performs action and waits for a `ConsoleMessage` to be logged by in the page. If predicate is provided, it passes `ConsoleMessage` value into the `predicate` function and waits for `predicate(message)` to return a truthy value. Will throw an error if the page is closed before the [`event: Page.console`] event is fired.
# File lib/playwright_api/page.rb, line 1082 def expect_console_message(predicate: nil, timeout: nil, &block) wrap_impl(@impl.expect_console_message(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end
Performs action and waits for a new `Download`. If predicate is provided, it passes `Download` value into the `predicate` function and waits for `predicate(download)` to return a truthy value. Will throw an error if the page is closed before the download event is fired.
# File lib/playwright_api/page.rb, line 1089 def expect_download(predicate: nil, timeout: nil, &block) wrap_impl(@impl.expect_download(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end
Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy value. Will throw an error if the page is closed before the event is fired. Returns the event data value.
“`python sync with page.expect_event(“framenavigated”) as event_info:
page.click("button")
frame = event_info.value “`
# File lib/playwright_api/page.rb, line 1101 def expect_event(event, predicate: nil, timeout: nil, &block) wrap_impl(@impl.expect_event(unwrap_impl(event), predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end
Performs action and waits for a new `FileChooser` to be created. If predicate is provided, it passes `FileChooser` value into the `predicate` function and waits for `predicate(fileChooser)` to return a truthy value. Will throw an error if the page is closed before the file chooser is opened.
# File lib/playwright_api/page.rb, line 1108 def expect_file_chooser(predicate: nil, timeout: nil, &block) wrap_impl(@impl.expect_file_chooser(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end
Performs action and waits for a popup `Page`. If predicate is provided, it passes [Popup] value into the `predicate` function and waits for `predicate(page)` to return a truthy value. Will throw an error if the page is closed before the popup event is fired.
# File lib/playwright_api/page.rb, line 1192 def expect_popup(predicate: nil, timeout: nil, &block) wrap_impl(@impl.expect_popup(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end
Waits for the matching request and returns it. See [waiting for event](./events.md#waiting-for-event) for more details about events.
“`python sync with page.expect_request(“example.com/resource”) as first:
page.click('button')
first_request = first.value
# or with a lambda with page.expect_request(lambda request: request.url == “example.com” and request.method == “get”) as second:
page.click('img')
second_request = second.value “`
# File lib/playwright_api/page.rb, line 1209 def expect_request(urlOrPredicate, timeout: nil, &block) wrap_impl(@impl.expect_request(unwrap_impl(urlOrPredicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end
Performs action and waits for a `Request` to finish loading. If predicate is provided, it passes `Request` value into the `predicate` function and waits for `predicate(request)` to return a truthy value. Will throw an error if the page is closed before the [`event: Page.requestFinished`] event is fired.
# File lib/playwright_api/page.rb, line 1216 def expect_request_finished(predicate: nil, timeout: nil, &block) wrap_impl(@impl.expect_request_finished(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end
Returns the matched response. See [waiting for event](./events.md#waiting-for-event) for more details about events.
“`python sync with page.expect_response(“example.com/resource”) as response_info:
page.click("input")
response = response_info.value return response.ok
# or with a lambda with page.expect_response(lambda response: response.url == “example.com” and response.status === 200) as response_info:
page.click("input")
response = response_info.value return response.ok “`
# File lib/playwright_api/page.rb, line 1234 def expect_response(urlOrPredicate, timeout: nil, &block) wrap_impl(@impl.expect_response(unwrap_impl(urlOrPredicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end
Performs action and waits for a new `WebSocket`. If predicate is provided, it passes `WebSocket` value into the `predicate` function and waits for `predicate(webSocket)` to return a truthy value. Will throw an error if the page is closed before the WebSocket
event is fired.
# File lib/playwright_api/page.rb, line 1297 def expect_websocket(predicate: nil, timeout: nil, &block) wrap_impl(@impl.expect_websocket(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end
Performs action and waits for a new `Worker`. If predicate is provided, it passes `Worker` value into the `predicate` function and waits for `predicate(worker)` to return a truthy value. Will throw an error if the page is closed before the worker event is fired.
# File lib/playwright_api/page.rb, line 1304 def expect_worker(predicate: nil, timeout: nil, &block) wrap_impl(@impl.expect_worker(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end
The method adds a function called `name` on the `window` object of every frame in this page. When called, the function executes `callback` and returns a [Promise] which resolves to the return value of `callback`. If the `callback` returns a [Promise], it will be awaited.
The first argument of the `callback` function contains information about the caller: `{ browserContext: BrowserContext
, page: Page
, frame: Frame
}`.
See [`method: BrowserContext.exposeBinding`] for the context-wide version.
> NOTE: Functions installed via [`method: Page.exposeBinding`] survive navigations.
An example of exposing page URL to all frames in a page:
“`python sync from playwright.sync_api import sync_playwright
def run(playwright):
webkit = playwright.webkit browser = webkit.launch(headless=false) context = browser.new_context() page = context.new_page() page.expose_binding("pageURL", lambda source: source["page"].url) page.set_content(""" <script> async function onClick() { document.querySelector('div').textContent = await window.pageURL(); } </script> <button onclick="onClick()">Click me</button> <div></div> """) page.click("button")
with sync_playwright() as playwright:
run(playwright)
“`
An example of passing an element handle:
“`python sync def print(source, element):
print(element.text_content())
page.expose_binding(“clicked”, print, handle=true) page.set_content(“”“
<script> document.addEventListener('click', event => window.clicked(event.target)); </script> <div>Click me</div> <div>Or click me</div>
“”“) “`
# File lib/playwright_api/page.rb, line 445 def expose_binding(name, callback, handle: nil) wrap_impl(@impl.expose_binding(unwrap_impl(name), unwrap_impl(callback), handle: unwrap_impl(handle))) end
The method adds a function called `name` on the `window` object of every frame in the page. When called, the function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
If the `callback` returns a [Promise], it will be awaited.
See [`method: BrowserContext.exposeFunction`] for context-wide exposed function.
> NOTE: Functions installed via [`method: Page.exposeFunction`] survive navigations.
An example of adding a `sha256` function to the page:
“`python sync import hashlib from playwright.sync_api import sync_playwright
def sha256(text):
m = hashlib.sha256() m.update(bytes(text, "utf8")) return m.hexdigest()
def run(playwright):
webkit = playwright.webkit browser = webkit.launch(headless=False) page = browser.new_page() page.expose_function("sha256", sha256) page.set_content(""" <script> async function onClick() { document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT'); } </script> <button onclick="onClick()">Click me</button> <div></div> """) page.click("button")
with sync_playwright() as playwright:
run(playwright)
“`
# File lib/playwright_api/page.rb, line 489 def expose_function(name, callback) wrap_impl(@impl.expose_function(unwrap_impl(name), unwrap_impl(callback))) end
This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling. Note that you can pass an empty string to clear the input field.
If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error. However, if the element is inside the `<label>` element that has an associated [control](developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled instead.
To send fine-grained keyboard events, use [`method: Page.type
`].
Shortcut for main frame's [`method: Frame.fill
`].
# File lib/playwright_api/page.rb, line 505 def fill( selector, value, force: nil, noWaitAfter: nil, strict: nil, timeout: nil) wrap_impl(@impl.fill(unwrap_impl(selector), unwrap_impl(value), force: unwrap_impl(force), noWaitAfter: unwrap_impl(noWaitAfter), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the method waits until a matching element appears in the DOM.
Shortcut for main frame's [`method: Frame.focus
`].
# File lib/playwright_api/page.rb, line 519 def focus(selector, strict: nil, timeout: nil) wrap_impl(@impl.focus(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
Returns frame matching the specified criteria. Either `name` or `url` must be specified.
“`py frame = page.frame(name=“frame-name”) “`
“`py frame = page.frame(url=r“.domain.”) “`
# File lib/playwright_api/page.rb, line 532 def frame(name: nil, url: nil) wrap_impl(@impl.frame(name: unwrap_impl(name), url: unwrap_impl(url))) end
An array of all frames attached to the page.
# File lib/playwright_api/page.rb, line 537 def frames wrap_impl(@impl.frames) end
Returns element attribute value.
# File lib/playwright_api/page.rb, line 542 def get_attribute(selector, name, strict: nil, timeout: nil) wrap_impl(@impl.get_attribute(unwrap_impl(selector), unwrap_impl(name), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, returns `null`.
Navigate to the previous page in history.
# File lib/playwright_api/page.rb, line 550 def go_back(timeout: nil, waitUntil: nil) wrap_impl(@impl.go_back(timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil))) end
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, returns `null`.
Navigate to the next page in history.
# File lib/playwright_api/page.rb, line 558 def go_forward(timeout: nil, waitUntil: nil) wrap_impl(@impl.go_forward(timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil))) end
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
`page.goto` will throw an error if:
-
there's an SSL error (e.g. in case of self-signed certificates).
-
target URL is invalid.
-
the `timeout` is exceeded during navigation.
-
the remote server does not respond or is unreachable.
-
the main resource failed to load.
`page.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404 “Not Found” and 500 “Internal Server Error”. The status code for such responses can be retrieved by calling [`method: Response.status
`].
> NOTE: `page.goto` either throws an error or returns a main resource response. The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`. > NOTE: Headless mode doesn't support navigation to a PDF document. See the [upstream issue](bugs.chromium.org/p/chromium/issues/detail?id=761295).
Shortcut for main frame's [`method: Frame.goto
`]
# File lib/playwright_api/page.rb, line 582 def goto(url, referer: nil, timeout: nil, waitUntil: nil) wrap_impl(@impl.goto(unwrap_impl(url), referer: unwrap_impl(referer), timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil))) end
@nodoc
# File lib/playwright_api/page.rb, line 1351 def guid wrap_impl(@impl.guid) end
This method hovers over an element matching `selector` by performing the following steps:
-
Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
-
Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
-
Scroll the element into view if needed.
-
Use [`property:
Page.mouse
`] to hover over the center of the element, or the specified `position`. -
Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`. Passing zero timeout disables this.
Shortcut for main frame's [`method: Frame.hover
`].
# File lib/playwright_api/page.rb, line 598 def hover( selector, force: nil, modifiers: nil, position: nil, strict: nil, timeout: nil, trial: nil) wrap_impl(@impl.hover(unwrap_impl(selector), force: unwrap_impl(force), modifiers: unwrap_impl(modifiers), position: unwrap_impl(position), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial))) end
Returns `element.innerHTML`.
# File lib/playwright_api/page.rb, line 610 def inner_html(selector, strict: nil, timeout: nil) wrap_impl(@impl.inner_html(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
Returns `element.innerText`.
# File lib/playwright_api/page.rb, line 615 def inner_text(selector, strict: nil, timeout: nil) wrap_impl(@impl.inner_text(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element. Throws for non-input elements.
# File lib/playwright_api/page.rb, line 620 def input_value(selector, strict: nil, timeout: nil) wrap_impl(@impl.input_value(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
# File lib/playwright_api/page.rb, line 51 def keyboard # property wrap_impl(@impl.keyboard) end
The method returns an element locator that can be used to perform actions on the page. Locator
is resolved to the element immediately before performing an action, so a series of actions on the same locator can in fact be performed on different DOM elements. That would happen if the DOM structure between those actions has changed.
Note that locator always implies visibility, so it will always be locating visible elements.
Shortcut for main frame's [`method: Frame.locator
`].
# File lib/playwright_api/page.rb, line 668 def locator(selector) wrap_impl(@impl.locator(unwrap_impl(selector))) end
The page's main frame. Page
is guaranteed to have a main frame which persists during navigations.
# File lib/playwright_api/page.rb, line 673 def main_frame wrap_impl(@impl.main_frame) end
# File lib/playwright_api/page.rb, line 55 def mouse # property wrap_impl(@impl.mouse) end
– inherited from EventEmitter
– @nodoc
# File lib/playwright_api/page.rb, line 1369 def off(event, callback) event_emitter_proxy.off(event, callback) end
– inherited from EventEmitter
– @nodoc
# File lib/playwright_api/page.rb, line 1363 def on(event, callback) event_emitter_proxy.on(event, callback) end
– inherited from EventEmitter
– @nodoc
# File lib/playwright_api/page.rb, line 1357 def once(event, callback) event_emitter_proxy.once(event, callback) end
Returns the opener for popup pages and `null` for others. If the opener has been closed already the returns `null`.
# File lib/playwright_api/page.rb, line 678 def opener wrap_impl(@impl.opener) end
@nodoc
# File lib/playwright_api/page.rb, line 1326 def owned_context=(req) wrap_impl(@impl.owned_context=(unwrap_impl(req))) end
Pauses script execution. Playwright
will stop executing the script and wait for the user to either press 'Resume' button in the page overlay or to call `playwright.resume()` in the DevTools console.
User can inspect selectors or perform manual steps while paused. Resume will continue running the original script from the place it was paused.
> NOTE: This method requires Playwright
to be started in a headed mode, with a falsy `headless` value in the [`method: BrowserType.launch
`].
# File lib/playwright_api/page.rb, line 690 def pause wrap_impl(@impl.pause) end
Returns the PDF buffer.
> NOTE: Generating a pdf is currently only supported in Chromium headless.
`page.pdf()` generates a pdf of the page with `print` css media. To generate a pdf with `screen` media, call
- `method: Page.emulateMedia`
-
before calling `page.pdf()`:
> NOTE: By default, `page.pdf()` generates a pdf with modified colors for printing. Use the [`-webkit-print-color-adjust`](developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust) property to force rendering of exact colors.
“`python sync # generates a pdf with “screen” media type. page.emulate_media(media=“screen”) page.pdf(path=“page.pdf”) “`
The `width`, `height`, and `margin` options accept values labeled with units. Unlabeled values are treated as pixels.
A few examples:
-
`page.pdf({width: 100})` - prints with width set to 100 pixels
-
`page.pdf({width: '100px'})` - prints with width set to 100 pixels
-
`page.pdf({width: '10cm'})` - prints with width set to 10 centimeters.
All possible units are:
-
`px` - pixel
-
`in` - inch
-
`cm` - centimeter
-
`mm` - millimeter
The `format` options are:
-
`Letter`: 8.5in x 11in
-
`Legal`: 8.5in x 14in
-
`Tabloid`: 11in x 17in
-
`Ledger`: 17in x 11in
-
`A0`: 33.1in x 46.8in
-
`A1`: 23.4in x 33.1in
-
`A2`: 16.54in x 23.4in
-
`A3`: 11.7in x 16.54in
-
`A4`: 8.27in x 11.7in
-
`A5`: 5.83in x 8.27in
-
`A6`: 4.13in x 5.83in
> NOTE: `headerTemplate` and `footerTemplate` markup have the following limitations: > 1. Script tags inside templates are not evaluated. > 2. Page
styles are not visible inside templates.
# File lib/playwright_api/page.rb, line 739 def pdf( displayHeaderFooter: nil, footerTemplate: nil, format: nil, headerTemplate: nil, height: nil, landscape: nil, margin: nil, pageRanges: nil, path: nil, preferCSSPageSize: nil, printBackground: nil, scale: nil, width: nil) wrap_impl(@impl.pdf(displayHeaderFooter: unwrap_impl(displayHeaderFooter), footerTemplate: unwrap_impl(footerTemplate), format: unwrap_impl(format), headerTemplate: unwrap_impl(headerTemplate), height: unwrap_impl(height), landscape: unwrap_impl(landscape), margin: unwrap_impl(margin), pageRanges: unwrap_impl(pageRanges), path: unwrap_impl(path), preferCSSPageSize: unwrap_impl(preferCSSPageSize), printBackground: unwrap_impl(printBackground), scale: unwrap_impl(scale), width: unwrap_impl(width))) end
Focuses the element, and then uses [`method: Keyboard.down
`] and [`method: Keyboard.up
`].
`key` can specify the intended [keyboardEvent.key](developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character to generate the text for. A superset of the `key` values can be found [here](developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
`F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`, `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective texts.
Shortcuts such as `key: “Control+o”` or `key: “Control+Shift+T”` are supported as well. When specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
“`python sync page = browser.new_page() page.goto(“keycode.info”) page.press(“body”, “A”) page.screenshot(path=“a.png”) page.press(“body”, “ArrowLeft”) page.screenshot(path=“arrow_left.png”) page.press(“body”, “Shift+O”) page.screenshot(path=“o.png”) browser.close() “`
# File lib/playwright_api/page.rb, line 786 def press( selector, key, delay: nil, noWaitAfter: nil, strict: nil, timeout: nil) wrap_impl(@impl.press(unwrap_impl(selector), unwrap_impl(key), delay: unwrap_impl(delay), noWaitAfter: unwrap_impl(noWaitAfter), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves to `null`. To wait for an element on the page, use [`method: Page.waitForSelector`].
Shortcut for main frame's [`method: Frame.querySelector`].
# File lib/playwright_api/page.rb, line 800 def query_selector(selector, strict: nil) wrap_impl(@impl.query_selector(unwrap_impl(selector), strict: unwrap_impl(strict))) end
The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to `[]`.
Shortcut for main frame's [`method: Frame.querySelectorAll`].
# File lib/playwright_api/page.rb, line 808 def query_selector_all(selector) wrap_impl(@impl.query_selector_all(unwrap_impl(selector))) end
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
# File lib/playwright_api/page.rb, line 814 def reload(timeout: nil, waitUntil: nil) wrap_impl(@impl.reload(timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil))) end
Routing provides the capability to modify network requests that are made by a page.
Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
> NOTE: The handler will only be called for the first url if the response is a redirect.
An example of a naive handler that aborts all image requests:
“`python sync page = browser.new_page() page.route(“*/.{png,jpg,jpeg}”, lambda route: route.abort()) page.goto(“example.com”) browser.close() “`
or the same snippet using a regex pattern instead:
“`python sync page = browser.new_page() page.route(re.compile(r“(.png$)|(.jpg$)”), lambda route: route.abort()) page.goto(“example.com”) browser.close() “`
It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:
“`python sync def handle_route(route):
if ("my-string" in route.request.post_data) route.fulfill(body="mocked-data") else route.continue_()
page.route(“/api/**”, handle_route) “`
Page
routes take precedence over browser context routes (set up with [`method: BrowserContext.route
`]) when request matches both handlers.
To remove a route with its handler you can use [`method: Page.unroute
`].
> NOTE: Enabling routing disables http cache.
# File lib/playwright_api/page.rb, line 860 def route(url, handler) wrap_impl(@impl.route(unwrap_impl(url), unwrap_impl(handler))) end
Returns the buffer with the captured screenshot.
# File lib/playwright_api/page.rb, line 865 def screenshot( clip: nil, fullPage: nil, omitBackground: nil, path: nil, quality: nil, timeout: nil, type: nil) wrap_impl(@impl.screenshot(clip: unwrap_impl(clip), fullPage: unwrap_impl(fullPage), omitBackground: unwrap_impl(omitBackground), path: unwrap_impl(path), quality: unwrap_impl(quality), timeout: unwrap_impl(timeout), type: unwrap_impl(type))) end
This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, waits until all specified options are present in the `<select>` element and selects these options.
If the target element is not a `<select>` element, this method throws an error. However, if the element is inside the `<label>` element that has an associated [control](developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used instead.
Returns the array of option values that have been successfully selected.
Triggers a `change` and `input` event once all the provided options have been selected.
“`python sync # single selection matching the value page.select_option(“select#colors”, “blue”) # single selection matching both the label page.select_option(“select#colors”, label=“blue”) # multiple selection page.select_option(“select#colors”, value=[“red”, “green”, “blue”]) “`
Shortcut for main frame's [`method: Frame.selectOption`].
# File lib/playwright_api/page.rb, line 897 def select_option( selector, element: nil, index: nil, value: nil, label: nil, force: nil, noWaitAfter: nil, strict: nil, timeout: nil) wrap_impl(@impl.select_option(unwrap_impl(selector), element: unwrap_impl(element), index: unwrap_impl(index), value: unwrap_impl(value), label: unwrap_impl(label), force: unwrap_impl(force), noWaitAfter: unwrap_impl(noWaitAfter), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
# File lib/playwright_api/page.rb, line 910 def set_content(html, timeout: nil, waitUntil: nil) wrap_impl(@impl.set_content(unwrap_impl(html), timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil))) end
This setting will change the default maximum time for all the methods accepting `timeout` option.
> NOTE: [`method: Page.setDefaultNavigationTimeout`] takes priority over [`method: Page.setDefaultTimeout`].
# File lib/playwright_api/page.rb, line 934 def set_default_timeout(timeout) wrap_impl(@impl.set_default_timeout(unwrap_impl(timeout))) end
The extra HTTP headers will be sent with every request the page initiates.
> NOTE: [`method: Page.setExtraHTTPHeaders`] does not guarantee the order of headers in the outgoing requests.
# File lib/playwright_api/page.rb, line 942 def set_extra_http_headers(headers) wrap_impl(@impl.set_extra_http_headers(unwrap_impl(headers))) end
This method expects `selector` to point to an [input element](developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then they are resolved relative to the the current working directory. For empty array, clears the selected files.
# File lib/playwright_api/page.rb, line 952 def set_input_files( selector, files, noWaitAfter: nil, strict: nil, timeout: nil) wrap_impl(@impl.set_input_files(unwrap_impl(selector), unwrap_impl(files), noWaitAfter: unwrap_impl(noWaitAfter), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
In the case of multiple pages in a single browser, each page can have its own viewport size. However,
- `method: Browser.newContext`
-
allows to set viewport size (and more) for all pages in the context at once.
`page.setViewportSize` will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport size before navigating to the page.
“`python sync page = browser.new_page() page.set_viewport_size({“width”: 640, “height”: 480}) page.goto(“example.com”) “`
# File lib/playwright_api/page.rb, line 972 def set_viewport_size(viewportSize) wrap_impl(@impl.set_viewport_size(unwrap_impl(viewportSize))) end
@nodoc
# File lib/playwright_api/page.rb, line 1341 def start_css_coverage(resetOnNavigation: nil, reportAnonymousScripts: nil) wrap_impl(@impl.start_css_coverage(resetOnNavigation: unwrap_impl(resetOnNavigation), reportAnonymousScripts: unwrap_impl(reportAnonymousScripts))) end
@nodoc
# File lib/playwright_api/page.rb, line 1331 def start_js_coverage(resetOnNavigation: nil, reportAnonymousScripts: nil) wrap_impl(@impl.start_js_coverage(resetOnNavigation: unwrap_impl(resetOnNavigation), reportAnonymousScripts: unwrap_impl(reportAnonymousScripts))) end
@nodoc
# File lib/playwright_api/page.rb, line 1346 def stop_css_coverage wrap_impl(@impl.stop_css_coverage) end
@nodoc
# File lib/playwright_api/page.rb, line 1336 def stop_js_coverage wrap_impl(@impl.stop_js_coverage) end
This method taps an element matching `selector` by performing the following steps:
-
Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
-
Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
-
Scroll the element into view if needed.
-
Use [`property:
Page.touchscreen
`] to tap the center of the element, or the specified `position`. -
Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`. Passing zero timeout disables this.
> NOTE: [`method: Page.tap`] requires that the `hasTouch` option of the browser context be set to true.
Shortcut for main frame's [`method: Frame.tap`].
# File lib/playwright_api/page.rb, line 991 def tap_point( selector, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) wrap_impl(@impl.tap_point(unwrap_impl(selector), force: unwrap_impl(force), modifiers: unwrap_impl(modifiers), noWaitAfter: unwrap_impl(noWaitAfter), position: unwrap_impl(position), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial))) end
Returns `element.textContent`.
# File lib/playwright_api/page.rb, line 1004 def text_content(selector, strict: nil, timeout: nil) wrap_impl(@impl.text_content(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
Returns the page's title. Shortcut for main frame's [`method: Frame.title
`].
# File lib/playwright_api/page.rb, line 1009 def title wrap_impl(@impl.title) end
# File lib/playwright_api/page.rb, line 59 def touchscreen # property wrap_impl(@impl.touchscreen) end
Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `page.type` can be used to send fine-grained keyboard events. To fill values in form fields, use [`method: Page.fill
`].
To press a special key, like `Control` or `ArrowDown`, use [`method: Keyboard.press
`].
“`python sync page.type(“#mytextarea”, “hello”) # types instantly page.type(“#mytextarea”, “world”, delay=100) # types slower, like a user “`
Shortcut for main frame's [`method: Frame.type
`].
# File lib/playwright_api/page.rb, line 1024 def type( selector, text, delay: nil, noWaitAfter: nil, strict: nil, timeout: nil) wrap_impl(@impl.type(unwrap_impl(selector), unwrap_impl(text), delay: unwrap_impl(delay), noWaitAfter: unwrap_impl(noWaitAfter), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
This method unchecks an element matching `selector` by performing the following steps:
-
Find an element matching `selector`. If there is none, wait until a matching element is attached to the DOM.
-
Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already unchecked, this method returns immediately.
-
Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
-
Scroll the element into view if needed.
-
Use [`property:
Page.mouse
`] to click in the center of the element. -
Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
-
Ensure that the element is now unchecked. If not, this method throws.
When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`. Passing zero timeout disables this.
Shortcut for main frame's [`method: Frame.uncheck
`].
# File lib/playwright_api/page.rb, line 1049 def uncheck( selector, force: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) wrap_impl(@impl.uncheck(unwrap_impl(selector), force: unwrap_impl(force), noWaitAfter: unwrap_impl(noWaitAfter), position: unwrap_impl(position), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout), trial: unwrap_impl(trial))) end
Removes a route created with [`method: Page.route
`]. When `handler` is not specified, removes all routes for the `url`.
# File lib/playwright_api/page.rb, line 1061 def unroute(url, handler: nil) wrap_impl(@impl.unroute(unwrap_impl(url), handler: unwrap_impl(handler))) end
Shortcut for main frame's [`method: Frame.url
`].
# File lib/playwright_api/page.rb, line 1066 def url wrap_impl(@impl.url) end
Video
object associated with this page.
# File lib/playwright_api/page.rb, line 1071 def video wrap_impl(@impl.video) end
# File lib/playwright_api/page.rb, line 1075 def viewport_size wrap_impl(@impl.viewport_size) end
Returns whether the element is [visible](./actionability.md#visible). `selector` that does not match any elements is considered not visible.
# File lib/playwright_api/page.rb, line 657 def visible?(selector, strict: nil, timeout: nil) wrap_impl(@impl.visible?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
> NOTE: In most cases, you should use [`method: Page.waitForEvent`].
Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function and waits for `predicate(event)` to return a truthy value. Will throw an error if the page is closed before the `event` is fired.
# File lib/playwright_api/page.rb, line 1321 def wait_for_event(event, predicate: nil, timeout: nil) raise NotImplementedError.new('wait_for_event is not implemented yet.') end
Returns when the `expression` returns a truthy value. It resolves to a JSHandle
of the truthy value.
The [`method: Page.waitForFunction`] can be used to observe viewport size change:
“`python sync from playwright.sync_api import sync_playwright
def run(playwright):
webkit = playwright.webkit browser = webkit.launch() page = browser.new_page() page.evaluate("window.x = 0; setTimeout(() => { window.x = 100 }, 1000);") page.wait_for_function("() => window.x > 0") browser.close()
with sync_playwright() as playwright:
run(playwright)
“`
To pass an argument to the predicate of [`method: Page.waitForFunction`] function:
“`python sync selector = “.foo” page.wait_for_function(“selector => !!document.querySelector(selector)”, selector) “`
Shortcut for main frame's [`method: Frame.waitForFunction`].
# File lib/playwright_api/page.rb, line 1139 def wait_for_function(expression, arg: nil, polling: nil, timeout: nil) wrap_impl(@impl.wait_for_function(unwrap_impl(expression), arg: unwrap_impl(arg), polling: unwrap_impl(polling), timeout: unwrap_impl(timeout))) end
Returns when the required load state has been reached.
This resolves when the page reaches a required load state, `load` by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.
“`python sync page.click(“button”) # click triggers navigation. page.wait_for_load_state() # the promise resolves after “load” event. “`
“`python sync with page.expect_popup() as page_info:
page.click("button") # click triggers a popup.
popup = page_info.value
# Following resolves after "domcontentloaded" event.
popup.wait_for_load_state(“domcontentloaded”) print(popup.title()) # popup is ready to use. “`
Shortcut for main frame's [`method: Frame.waitForLoadState`].
# File lib/playwright_api/page.rb, line 1163 def wait_for_load_state(state: nil, timeout: nil) wrap_impl(@impl.wait_for_load_state(state: unwrap_impl(state), timeout: unwrap_impl(timeout))) end
Returns when element specified by selector satisfies `state` option. Returns `null` if waiting for `hidden` or `detached`.
Wait for the `selector` to satisfy `state` option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the function will throw.
This method works across navigations:
“`python sync from playwright.sync_api import sync_playwright
def run(playwright):
chromium = playwright.chromium browser = chromium.launch() page = browser.new_page() for current_url in ["https://google.com", "https://bbc.com"]: page.goto(current_url, wait_until="domcontentloaded") element = page.wait_for_selector("img") print("Loaded image: " + str(element.get_attribute("src"))) browser.close()
with sync_playwright() as playwright:
run(playwright)
“`
# File lib/playwright_api/page.rb, line 1263 def wait_for_selector(selector, state: nil, strict: nil, timeout: nil) wrap_impl(@impl.wait_for_selector(unwrap_impl(selector), state: unwrap_impl(state), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end
Waits for the given `timeout` in milliseconds.
Note that `page.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.
“`python sync # wait for 1 second page.wait_for_timeout(1000) “`
Shortcut for main frame's [`method: Frame.waitForTimeout`].
# File lib/playwright_api/page.rb, line 1278 def wait_for_timeout(timeout) wrap_impl(@impl.wait_for_timeout(unwrap_impl(timeout))) end
Waits for the main frame to navigate to the given URL.
“`python sync page.click(“a.delayed-navigation”) # clicking the link will indirectly cause a navigation page.wait_for_url(“**/target.html”) “`
Shortcut for main frame's [`method: Frame.waitForURL`].
# File lib/playwright_api/page.rb, line 1290 def wait_for_url(url, timeout: nil, waitUntil: nil) wrap_impl(@impl.wait_for_url(unwrap_impl(url), timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil))) end
This method returns all of the dedicated [WebWorkers](developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page.
> NOTE: This does not contain ServiceWorkers
# File lib/playwright_api/page.rb, line 1312 def workers wrap_impl(@impl.workers) end
Private Instance Methods
# File lib/playwright_api/page.rb, line 1373 def event_emitter_proxy @event_emitter_proxy ||= EventEmitterProxy.new(self, @impl) end