Class: Playwright::Page
- Inherits:
-
PlaywrightApi
- Object
- PlaywrightApi
- Playwright::Page
- Defined in:
- lib/playwright_api/page.rb
Overview
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, 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)
“‘
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) “‘
Instance Method Summary collapse
-
#accessibility ⇒ Object
property.
-
#add_init_script(path: nil, script: nil) ⇒ Object
Adds a script which would be evaluated in one of the following scenarios: - Whenever the page is navigated.
-
#add_locator_handler(locator, handler, noWaitAfter: nil, times: nil) ⇒ Object
When testing a web page, sometimes unexpected overlays like a “Sign up” dialog appear and block actions you want to automate, e.g.
-
#add_script_tag(content: nil, path: nil, type: nil, url: nil) ⇒ Object
Adds a ‘<script>` tag into the page with the desired url or content.
-
#add_style_tag(content: nil, path: nil, url: nil) ⇒ Object
Adds a ‘<link rel=“stylesheet”>` tag into the page with the desired url or a `<style type=“text/css”>` tag with the content.
-
#bring_to_front ⇒ Object
Brings page to front (activates tab).
-
#check(selector, force: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ Object
This method checks an element matching ‘selector` by performing the following steps: 1.
-
#checked?(selector, strict: nil, timeout: nil) ⇒ Boolean
Returns whether the element is checked.
-
#click(selector, button: nil, clickCount: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ Object
This method clicks an element matching ‘selector` by performing the following steps: 1.
-
#clock ⇒ Object
Playwright has ability to mock clock and passage of time.
-
#close(reason: nil, runBeforeUnload: nil) ⇒ Object
If ‘runBeforeUnload` is `false`, does not run any unload handlers and waits for the page to be closed.
-
#closed? ⇒ Boolean
Indicates that the page has been closed.
-
#content ⇒ Object
Gets the full HTML contents of the page, including the doctype.
-
#context ⇒ Object
Get the browser context that the page belongs to.
-
#dblclick(selector, button: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ Object
This method double clicks an element matching ‘selector` by performing the following steps: 1.
-
#disabled?(selector, strict: nil, timeout: nil) ⇒ Boolean
Returns whether the element is disabled, the opposite of [enabled](../actionability.md#enabled).
-
#dispatch_event(selector, type, eventInit: nil, strict: nil, timeout: nil) ⇒ Object
The snippet below dispatches the ‘click` event on the element.
-
#drag_and_drop(source, target, force: nil, noWaitAfter: nil, sourcePosition: nil, strict: nil, targetPosition: nil, timeout: nil, trial: nil) ⇒ Object
This method drags the source element to the target element.
-
#editable?(selector, strict: nil, timeout: nil) ⇒ Boolean
Returns whether the element is [editable](../actionability.md#editable).
-
#emulate_media(colorScheme: nil, forcedColors: nil, media: nil, reducedMotion: nil) ⇒ Object
This method changes the ‘CSS media type` through the `media` argument, and/or the `’prefers-colors-scheme’‘ media feature, using the `colorScheme` argument.
-
#enabled?(selector, strict: nil, timeout: nil) ⇒ Boolean
Returns whether the element is [enabled](../actionability.md#enabled).
-
#eval_on_selector(selector, expression, arg: nil, strict: nil) ⇒ Object
The method finds an element matching the specified selector within the page and passes it as a first argument to ‘expression`.
-
#eval_on_selector_all(selector, expression, arg: nil) ⇒ Object
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`.
-
#evaluate(expression, arg: nil) ⇒ Object
Returns the value of the ‘expression` invocation.
-
#evaluate_handle(expression, arg: nil) ⇒ Object
Returns the value of the ‘expression` invocation as a `JSHandle`.
-
#expect_console_message(predicate: nil, timeout: nil, &block) ⇒ Object
Performs action and waits for a ‘ConsoleMessage` to be logged by in the page.
-
#expect_download(predicate: nil, timeout: nil, &block) ⇒ Object
Performs action and waits for a new ‘Download`.
-
#expect_event(event, predicate: nil, timeout: nil, &block) ⇒ Object
Waits for event to fire and passes its value into the predicate function.
-
#expect_file_chooser(predicate: nil, timeout: nil, &block) ⇒ Object
Performs action and waits for a new ‘FileChooser` to be created.
-
#expect_navigation(timeout: nil, url: nil, waitUntil: nil, &block) ⇒ Object
deprecated
Deprecated.
This method is inherently racy, please use [‘method: Page.waitForURL`] instead.
-
#expect_popup(predicate: nil, timeout: nil, &block) ⇒ Object
Performs action and waits for a popup ‘Page`.
-
#expect_request(urlOrPredicate, timeout: nil, &block) ⇒ Object
Waits for the matching request and returns it.
-
#expect_request_finished(predicate: nil, timeout: nil, &block) ⇒ Object
Performs action and waits for a ‘Request` to finish loading.
-
#expect_response(urlOrPredicate, timeout: nil, &block) ⇒ Object
Returns the matched response.
-
#expect_websocket(predicate: nil, timeout: nil, &block) ⇒ Object
Performs action and waits for a new ‘WebSocket`.
-
#expect_worker(predicate: nil, timeout: nil, &block) ⇒ Object
Performs action and waits for a new ‘Worker`.
-
#expose_binding(name, callback, handle: nil) ⇒ Object
The method adds a function called ‘name` on the `window` object of every frame in this page.
-
#expose_function(name, callback) ⇒ Object
The method adds a function called ‘name` on the `window` object of every frame in the page.
-
#fill(selector, value, force: nil, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ Object
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.
-
#focus(selector, strict: nil, timeout: nil) ⇒ Object
This method fetches an element with ‘selector` and focuses it.
-
#frame(name: nil, url: nil) ⇒ Object
Returns frame matching the specified criteria.
-
#frame_locator(selector) ⇒ Object
When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements in that iframe.
-
#frames ⇒ Object
An array of all frames attached to the page.
-
#get_attribute(selector, name, strict: nil, timeout: nil) ⇒ Object
Returns element attribute value.
-
#get_by_alt_text(text, exact: nil) ⇒ Object
Allows locating elements by their alt text.
-
#get_by_label(text, exact: nil) ⇒ Object
Allows locating input elements by the text of the associated ‘<label>` or `aria-labelledby` element, or by the `aria-label` attribute.
-
#get_by_placeholder(text, exact: nil) ⇒ Object
Allows locating input elements by the placeholder text.
-
#get_by_role(role, checked: nil, disabled: nil, exact: nil, expanded: nil, includeHidden: nil, level: nil, name: nil, pressed: nil, selected: nil) ⇒ Object
Allows locating elements by their [ARIA role](www.w3.org/TR/wai-aria-1.2/#roles), [ARIA attributes](www.w3.org/TR/wai-aria-1.2/#aria-attributes) and [accessible name](w3c.github.io/accname/#dfn-accessible-name).
-
#get_by_test_id(testId) ⇒ Object
Locate element by the test id.
-
#get_by_text(text, exact: nil) ⇒ Object
Allows locating elements that contain given text.
-
#get_by_title(text, exact: nil) ⇒ Object
Allows locating elements by their title attribute.
-
#go_back(timeout: nil, waitUntil: nil) ⇒ Object
Returns the main resource response.
-
#go_forward(timeout: nil, waitUntil: nil) ⇒ Object
Returns the main resource response.
-
#goto(url, referer: nil, timeout: nil, waitUntil: nil) ⇒ Object
Returns the main resource response.
- #guid ⇒ Object
-
#hidden?(selector, strict: nil, timeout: nil) ⇒ Boolean
Returns whether the element is hidden, the opposite of [visible](../actionability.md#visible).
-
#hover(selector, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ Object
This method hovers over an element matching ‘selector` by performing the following steps: 1.
-
#inner_html(selector, strict: nil, timeout: nil) ⇒ Object
Returns ‘element.innerHTML`.
-
#inner_text(selector, strict: nil, timeout: nil) ⇒ Object
Returns ‘element.innerText`.
-
#input_value(selector, strict: nil, timeout: nil) ⇒ Object
Returns ‘input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
-
#keyboard ⇒ Object
property.
-
#locator(selector, has: nil, hasNot: nil, hasNotText: nil, hasText: nil) ⇒ Object
The method returns an element locator that can be used to perform actions on this page / frame.
-
#main_frame ⇒ Object
The page’s main frame.
-
#mouse ⇒ Object
property.
-
#off(event, callback) ⇒ Object
– inherited from EventEmitter –.
-
#on(event, callback) ⇒ Object
– inherited from EventEmitter –.
-
#once(event, callback) ⇒ Object
– inherited from EventEmitter –.
-
#opener ⇒ Object
Returns the opener for popup pages and ‘null` for others.
- #owned_context=(req) ⇒ Object
-
#pause ⇒ Object
Pauses script execution.
-
#pdf(displayHeaderFooter: nil, footerTemplate: nil, format: nil, headerTemplate: nil, height: nil, landscape: nil, margin: nil, outline: nil, pageRanges: nil, path: nil, preferCSSPageSize: nil, printBackground: nil, scale: nil, tagged: nil, width: nil) ⇒ Object
Returns the PDF buffer.
-
#press(selector, key, delay: nil, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ Object
Focuses the element, and then uses [‘method: Keyboard.down`] and [`method: Keyboard.up`].
-
#query_selector(selector, strict: nil) ⇒ Object
The method finds an element matching the specified selector within the page.
-
#query_selector_all(selector) ⇒ Object
The method finds all elements matching the specified selector within the page.
-
#reload(timeout: nil, waitUntil: nil) ⇒ Object
This method reloads the current page, in the same way as if the user had triggered a browser refresh.
-
#remove_locator_handler(locator) ⇒ Object
Removes all locator handlers added by [‘method: Page.addLocatorHandler`] for a specific locator.
-
#request ⇒ Object
API testing helper associated with this page.
-
#request_gc ⇒ Object
Request the page to perform garbage collection.
-
#route(url, handler, times: nil) ⇒ Object
Routing provides the capability to modify network requests that are made by a page.
-
#route_from_har(har, notFound: nil, update: nil, updateContent: nil, updateMode: nil, url: nil) ⇒ Object
If specified the network requests that are made in the page will be served from the HAR file.
-
#route_web_socket(url, handler) ⇒ Object
This method allows to modify websocket connections that are made by the page.
-
#screenshot(animations: nil, caret: nil, clip: nil, fullPage: nil, mask: nil, maskColor: nil, omitBackground: nil, path: nil, quality: nil, scale: nil, style: nil, timeout: nil, type: nil) ⇒ Object
Returns the buffer with the captured screenshot.
-
#select_option(selector, element: nil, index: nil, value: nil, label: nil, force: nil, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ Object
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.
-
#set_checked(selector, checked, force: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ Object
This method checks or unchecks an element matching ‘selector` by performing the following steps: 1.
-
#set_content(html, timeout: nil, waitUntil: nil) ⇒ Object
(also: #content=)
This method internally calls [document.write()](developer.mozilla.org/en-US/docs/Web/API/Document/write), inheriting all its specific characteristics and behaviors.
-
#set_default_navigation_timeout(timeout) ⇒ Object
(also: #default_navigation_timeout=)
This setting will change the default maximum navigation time for the following methods and related shortcuts: - [‘method: Page.goBack`] - [`method: Page.goForward`] - [`method: Page.goto`] - [`method: Page.reload`] - [`method: Page.setContent`] - [`method: Page.waitForNavigation`] - [`method: Page.waitForURL`].
-
#set_default_timeout(timeout) ⇒ Object
(also: #default_timeout=)
This setting will change the default maximum time for all the methods accepting ‘timeout` option.
-
#set_extra_http_headers(headers) ⇒ Object
(also: #extra_http_headers=)
The extra HTTP headers will be sent with every request the page initiates.
-
#set_input_files(selector, files, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ Object
Sets the value of the file input to these file paths or files.
-
#set_viewport_size(viewportSize) ⇒ Object
(also: #viewport_size=)
In the case of multiple pages in a single browser, each page can have its own viewport size.
- #start_css_coverage(resetOnNavigation: nil, reportAnonymousScripts: nil) ⇒ Object
- #start_js_coverage(resetOnNavigation: nil, reportAnonymousScripts: nil) ⇒ Object
- #stop_css_coverage ⇒ Object
- #stop_js_coverage ⇒ Object
-
#tap_point(selector, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ Object
This method taps an element matching ‘selector` by performing the following steps: 1.
-
#text_content(selector, strict: nil, timeout: nil) ⇒ Object
Returns ‘element.textContent`.
-
#title ⇒ Object
Returns the page’s title.
-
#touchscreen ⇒ Object
property.
-
#type(selector, text, delay: nil, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ Object
deprecated
Deprecated.
In most cases, you should use [‘method: Locator.fill`] instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use [`method: Locator.pressSequentially`].
-
#uncheck(selector, force: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ Object
This method unchecks an element matching ‘selector` by performing the following steps: 1.
-
#unroute(url, handler: nil) ⇒ Object
Removes a route created with [‘method: Page.route`].
-
#unroute_all(behavior: nil) ⇒ Object
Removes all routes created with [‘method: Page.route`] and [`method: Page.routeFromHAR`].
- #url ⇒ Object
-
#video ⇒ Object
Video object associated with this page.
- #viewport_size ⇒ Object
-
#visible?(selector, strict: nil, timeout: nil) ⇒ Boolean
Returns whether the element is [visible](../actionability.md#visible).
-
#wait_for_event(event, predicate: nil, timeout: nil) ⇒ Object
NOTE: In most cases, you should use [‘method: Page.waitForEvent`].
-
#wait_for_function(expression, arg: nil, polling: nil, timeout: nil) ⇒ Object
Returns when the ‘expression` returns a truthy value.
-
#wait_for_load_state(state: nil, timeout: nil) ⇒ Object
Returns when the required load state has been reached.
-
#wait_for_selector(selector, state: nil, strict: nil, timeout: nil) ⇒ Object
Returns when element specified by selector satisfies ‘state` option.
-
#wait_for_timeout(timeout) ⇒ Object
Waits for the given ‘timeout` in milliseconds.
-
#wait_for_url(url, timeout: nil, waitUntil: nil) ⇒ Object
Waits for the main frame to navigate to the given URL.
-
#workers ⇒ Object
This method returns all of the dedicated [WebWorkers](developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page.
Methods inherited from PlaywrightApi
Constructor Details
This class inherits a constructor from Playwright::PlaywrightApi
Instance Method Details
#accessibility ⇒ Object
property
52 53 54 |
# File 'lib/playwright_api/page.rb', line 52 def accessibility # property wrap_impl(@impl.accessibility) end |
#add_init_script(path: nil, script: nil) ⇒ Object
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`.
Usage
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.
94 95 96 |
# File 'lib/playwright_api/page.rb', line 94 def add_init_script(path: nil, script: nil) wrap_impl(@impl.add_init_script(path: unwrap_impl(path), script: unwrap_impl(script))) end |
#add_locator_handler(locator, handler, noWaitAfter: nil, times: nil) ⇒ Object
When 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 [‘method: Page.addLocatorHandler`].
-
Playwright checks for the overlay every time before executing or retrying an action that requires an [actionability check](../actionability.md), 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 ‘noWaitAfter`.
-
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.
NOTE: 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 [‘method: Locator.focus`] followed by [`method: 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 [`method: Locator.press`] instead to avoid this problem.
Another example is a series of mouse actions, where [‘method: Mouse.move`] is followed by [`method: 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 [`method: 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:
“‘python sync # 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(“example.com”) page.get_by_role(“button”, name=“Start here”).click() “‘
An example that skips the “Confirm your security details” page when it is shown:
“‘python sync # 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(“example.com”) 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 `noWaitAfter`, because the handler does not hide the `<body>` element.
“‘python sync # 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(“example.com”) 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`:
“‘python sync def handler(locator):
locator.click()
page.add_locator_handler(page.get_by_label(“Close”), handler, times=1) “‘
1151 1152 1153 |
# File 'lib/playwright_api/page.rb', line 1151 def add_locator_handler(locator, handler, noWaitAfter: nil, times: nil) raise NotImplementedError.new('add_locator_handler is not implemented yet.') end |
#add_script_tag(content: nil, path: nil, type: nil, url: nil) ⇒ Object
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.
101 102 103 |
# File 'lib/playwright_api/page.rb', line 101 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 |
#add_style_tag(content: nil, path: nil, url: nil) ⇒ Object
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.
108 109 110 |
# File 'lib/playwright_api/page.rb', line 108 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 |
#bring_to_front ⇒ Object
Brings page to front (activates tab).
114 115 116 |
# File 'lib/playwright_api/page.rb', line 114 def bring_to_front wrap_impl(@impl.bring_to_front) end |
#check(selector, force: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ Object
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.
-
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.
129 130 131 132 133 134 135 136 137 138 |
# File 'lib/playwright_api/page.rb', line 129 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 |
#checked?(selector, strict: nil, timeout: nil) ⇒ Boolean
Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
880 881 882 |
# File 'lib/playwright_api/page.rb', line 880 def checked?(selector, strict: nil, timeout: nil) wrap_impl(@impl.checked?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end |
#click(selector, button: nil, clickCount: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ Object
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.
150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
# File 'lib/playwright_api/page.rb', line 150 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(), 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 |
#clock ⇒ Object
Playwright has ability to mock clock and passage of time.
48 49 50 |
# File 'lib/playwright_api/page.rb', line 48 def clock # property wrap_impl(@impl.clock) end |
#close(reason: nil, runBeforeUnload: nil) ⇒ Object
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.
173 174 175 |
# File 'lib/playwright_api/page.rb', line 173 def close(reason: nil, runBeforeUnload: nil) wrap_impl(@impl.close(reason: unwrap_impl(reason), runBeforeUnload: unwrap_impl(runBeforeUnload))) end |
#closed? ⇒ Boolean
Indicates that the page has been closed.
886 887 888 |
# File 'lib/playwright_api/page.rb', line 886 def closed? wrap_impl(@impl.closed?) end |
#content ⇒ Object
Gets the full HTML contents of the page, including the doctype.
179 180 181 |
# File 'lib/playwright_api/page.rb', line 179 def content wrap_impl(@impl.content) end |
#context ⇒ Object
Get the browser context that the page belongs to.
185 186 187 |
# File 'lib/playwright_api/page.rb', line 185 def context wrap_impl(@impl.context) end |
#dblclick(selector, button: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ Object
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`.
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.
200 201 202 203 204 205 206 207 208 209 210 211 212 |
# File 'lib/playwright_api/page.rb', line 200 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(), 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 |
#disabled?(selector, strict: nil, timeout: nil) ⇒ Boolean
Returns whether the element is disabled, the opposite of [enabled](../actionability.md#enabled).
892 893 894 |
# File 'lib/playwright_api/page.rb', line 892 def disabled?(selector, strict: nil, timeout: nil) wrap_impl(@impl.disabled?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end |
#dispatch_event(selector, type, eventInit: nil, strict: nil, timeout: nil) ⇒ Object
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).
Usage
“‘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:
-
[DeviceMotionEvent](developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
-
[DeviceOrientationEvent](developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
-
[DragEvent](developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
-
[Event](developer.mozilla.org/en-US/docs/Web/API/Event/Event)
-
[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)
-
[WheelEvent](developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
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 }) “`
249 250 251 252 253 254 255 256 |
# File 'lib/playwright_api/page.rb', line 249 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 |
#drag_and_drop(source, target, force: nil, noWaitAfter: nil, sourcePosition: nil, strict: nil, targetPosition: nil, timeout: nil, trial: nil) ⇒ Object
This 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
“‘python sync 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}
) “‘
275 276 277 278 279 280 281 282 283 284 285 286 |
# File 'lib/playwright_api/page.rb', line 275 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 |
#editable?(selector, strict: nil, timeout: nil) ⇒ Boolean
Returns whether the element is [editable](../actionability.md#editable).
898 899 900 |
# File 'lib/playwright_api/page.rb', line 898 def editable?(selector, strict: nil, timeout: nil) wrap_impl(@impl.editable?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end |
#emulate_media(colorScheme: nil, forcedColors: nil, media: nil, reducedMotion: nil) ⇒ Object
This method changes the ‘CSS media type` through the `media` argument, and/or the `’prefers-colors-scheme’‘ media feature, using the `colorScheme` argument.
Usage
“‘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”) “`
320 321 322 |
# File 'lib/playwright_api/page.rb', line 320 def emulate_media(colorScheme: nil, forcedColors: nil, media: nil, reducedMotion: nil) wrap_impl(@impl.emulate_media(colorScheme: unwrap_impl(colorScheme), forcedColors: unwrap_impl(forcedColors), media: unwrap_impl(media), reducedMotion: unwrap_impl(reducedMotion))) end |
#enabled?(selector, strict: nil, timeout: nil) ⇒ Boolean
Returns whether the element is [enabled](../actionability.md#enabled).
904 905 906 |
# File 'lib/playwright_api/page.rb', line 904 def enabled?(selector, strict: nil, timeout: nil) wrap_impl(@impl.enabled?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end |
#eval_on_selector(selector, expression, arg: nil, strict: nil) ⇒ Object
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.
Usage
“‘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”) “`
339 340 341 |
# File 'lib/playwright_api/page.rb', line 339 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 |
#eval_on_selector_all(selector, expression, arg: nil) ⇒ Object
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.
Usage
“‘python sync div_counts = page.eval_on_selector_all(“div”, “(divs, min) => divs.length >= min”, 10) “`
355 356 357 |
# File 'lib/playwright_api/page.rb', line 355 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 |
#evaluate(expression, arg: nil) ⇒ Object
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`.
Usage
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.evaluate(“document.body”) html = page.evaluate(“([body, suffix]) => body.innerHTML + suffix”, [body_handle, “hello”]) body_handle.dispose() “`
393 394 395 |
# File 'lib/playwright_api/page.rb', line 393 def evaluate(expression, arg: nil) wrap_impl(@impl.evaluate(unwrap_impl(expression), arg: unwrap_impl(arg))) end |
#evaluate_handle(expression, arg: nil) ⇒ Object
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.
Usage
“‘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() “`
426 427 428 |
# File 'lib/playwright_api/page.rb', line 426 def evaluate_handle(expression, arg: nil) wrap_impl(@impl.evaluate_handle(unwrap_impl(expression), arg: unwrap_impl(arg))) end |
#expect_console_message(predicate: nil, timeout: nil, &block) ⇒ Object
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.
1517 1518 1519 |
# File 'lib/playwright_api/page.rb', line 1517 def (predicate: nil, timeout: nil, &block) wrap_impl(@impl.(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end |
#expect_download(predicate: nil, timeout: nil, &block) ⇒ Object
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.
1525 1526 1527 |
# File 'lib/playwright_api/page.rb', line 1525 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 |
#expect_event(event, predicate: nil, timeout: nil, &block) ⇒ Object
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.
Usage
“‘python sync with page.expect_event(“framenavigated”) as event_info:
page.get_by_role("button")
frame = event_info.value “‘
1540 1541 1542 |
# File 'lib/playwright_api/page.rb', line 1540 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 |
#expect_file_chooser(predicate: nil, timeout: nil, &block) ⇒ Object
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.
1548 1549 1550 |
# File 'lib/playwright_api/page.rb', line 1548 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 |
#expect_navigation(timeout: nil, url: nil, waitUntil: nil, &block) ⇒ Object
This method is inherently racy, please use [‘method: Page.waitForURL`] instead.
Waits for the main frame navigation and returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with ‘null`.
Usage
This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly cause the page to navigate. e.g. The click target has an ‘onclick` handler that triggers navigation from a `setTimeout`. Consider this example:
“‘python sync with page.expect_navigation():
# This action triggers the navigation after a timeout.
page.get_by_text("Navigate after timeout").click()
# Resolves after navigation has finished “‘
NOTE: Usage of the [History API](developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is considered a navigation.
1633 1634 1635 |
# File 'lib/playwright_api/page.rb', line 1633 def (timeout: nil, url: nil, waitUntil: nil, &block) wrap_impl(@impl.(timeout: unwrap_impl(timeout), url: unwrap_impl(url), waitUntil: unwrap_impl(waitUntil), &wrap_block_call(block))) end |
#expect_popup(predicate: nil, timeout: nil, &block) ⇒ Object
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.
1641 1642 1643 |
# File 'lib/playwright_api/page.rb', line 1641 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 |
#expect_request(urlOrPredicate, timeout: nil, &block) ⇒ Object
Waits for the matching request and returns it. See [waiting for event](../events.md#waiting-for-event) for more details about events.
Usage
“‘python sync with page.expect_request(“example.com/resource”) as first:
page.get_by_text("trigger request").click()
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.get_by_text("trigger request").click()
second_request = second.value “‘
1660 1661 1662 |
# File 'lib/playwright_api/page.rb', line 1660 def expect_request(urlOrPredicate, timeout: nil, &block) wrap_impl(@impl.expect_request(unwrap_impl(urlOrPredicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end |
#expect_request_finished(predicate: nil, timeout: nil, &block) ⇒ Object
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.
1668 1669 1670 |
# File 'lib/playwright_api/page.rb', line 1668 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 |
#expect_response(urlOrPredicate, timeout: nil, &block) ⇒ Object
Returns the matched response. See [waiting for event](../events.md#waiting-for-event) for more details about events.
Usage
“‘python sync with page.expect_response(“example.com/resource”) as response_info:
page.get_by_text("trigger response").click()
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 and response.request.method == “get”) as response_info:
page.get_by_text("trigger response").click()
response = response_info.value return response.ok “‘
1689 1690 1691 |
# File 'lib/playwright_api/page.rb', line 1689 def expect_response(urlOrPredicate, timeout: nil, &block) wrap_impl(@impl.expect_response(unwrap_impl(urlOrPredicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end |
#expect_websocket(predicate: nil, timeout: nil, &block) ⇒ Object
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.
1762 1763 1764 |
# File 'lib/playwright_api/page.rb', line 1762 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 |
#expect_worker(predicate: nil, timeout: nil, &block) ⇒ Object
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.
1770 1771 1772 |
# File 'lib/playwright_api/page.rb', line 1770 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 |
#expose_binding(name, callback, handle: nil) ⇒ Object
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.
Usage
An example of exposing page URL to all frames in a page:
“‘python sync from playwright.sync_api import sync_playwright, Playwright
def run(playwright: 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)
“‘
469 470 471 |
# File 'lib/playwright_api/page.rb', line 469 def expose_binding(name, callback, handle: nil) wrap_impl(@impl.expose_binding(unwrap_impl(name), unwrap_impl(callback), handle: unwrap_impl(handle))) end |
#expose_function(name, callback) ⇒ Object
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.
Usage
An example of adding a ‘sha256` function to the page:
“‘python sync import hashlib from playwright.sync_api import sync_playwright, Playwright
def sha256(text):
m = hashlib.sha256()
m.update(bytes(text, "utf8"))
return m.hexdigest()
def run(playwright: 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)
“‘
516 517 518 |
# File 'lib/playwright_api/page.rb', line 516 def expose_function(name, callback) wrap_impl(@impl.expose_function(unwrap_impl(name), unwrap_impl(callback))) end |
#fill(selector, value, force: nil, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ Object
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: Locator.pressSequentially`].
526 527 528 529 530 531 532 533 534 |
# File 'lib/playwright_api/page.rb', line 526 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 |
#focus(selector, strict: nil, timeout: nil) ⇒ Object
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.
539 540 541 |
# File 'lib/playwright_api/page.rb', line 539 def focus(selector, strict: nil, timeout: nil) wrap_impl(@impl.focus(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end |
#frame(name: nil, url: nil) ⇒ Object
Returns frame matching the specified criteria. Either ‘name` or `url` must be specified.
Usage
“‘py frame = page.frame(name=“frame-name”) “`
“‘py frame = page.frame(url=r“.domain.”) “`
555 556 557 |
# File 'lib/playwright_api/page.rb', line 555 def frame(name: nil, url: nil) wrap_impl(@impl.frame(name: unwrap_impl(name), url: unwrap_impl(url))) end |
#frame_locator(selector) ⇒ Object
When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements in that iframe.
Usage
Following snippet locates element with text “Submit” in the iframe with id ‘my-frame`, like `<iframe id=“my-frame”>`:
“‘python sync locator = page.frame_locator(“#my-iframe”).get_by_text(“Submit”) locator.click() “`
572 573 574 |
# File 'lib/playwright_api/page.rb', line 572 def frame_locator(selector) wrap_impl(@impl.frame_locator(unwrap_impl(selector))) end |
#frames ⇒ Object
An array of all frames attached to the page.
578 579 580 |
# File 'lib/playwright_api/page.rb', line 578 def frames wrap_impl(@impl.frames) end |
#get_attribute(selector, name, strict: nil, timeout: nil) ⇒ Object
Returns element attribute value.
584 585 586 |
# File 'lib/playwright_api/page.rb', line 584 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 |
#get_by_alt_text(text, exact: nil) ⇒ Object
Allows locating elements by their alt text.
Usage
For example, this method will find the image by alt text “Playwright logo”:
“‘html <img alt=’Playwright logo’> “‘
“‘python sync page.get_by_alt_text(“Playwright logo”).click() “`
602 603 604 |
# File 'lib/playwright_api/page.rb', line 602 def get_by_alt_text(text, exact: nil) wrap_impl(@impl.get_by_alt_text(unwrap_impl(text), exact: unwrap_impl(exact))) end |
#get_by_label(text, exact: nil) ⇒ Object
Allows locating input elements by the text of the associated ‘<label>` or `aria-labelledby` element, or by the `aria-label` attribute.
Usage
For example, this method will find inputs by label “Username” and “Password” in the following DOM:
“‘html <input aria-label=“Username”> <label for=“password-input”>Password:</label> <input id=“password-input”> “`
“‘python sync page.get_by_label(“Username”).fill(“john”) page.get_by_label(“Password”).fill(“secret”) “`
623 624 625 |
# File 'lib/playwright_api/page.rb', line 623 def get_by_label(text, exact: nil) wrap_impl(@impl.get_by_label(unwrap_impl(text), exact: unwrap_impl(exact))) end |
#get_by_placeholder(text, exact: nil) ⇒ Object
Allows locating input elements by the placeholder text.
Usage
For example, consider the following DOM structure.
“‘html <input type=“email” placeholder=“[email protected]” /> “`
You can fill the input after locating it by the placeholder text:
“‘python sync page.get_by_placeholder(“[email protected]”).fill(“[email protected]”) “`
643 644 645 |
# File 'lib/playwright_api/page.rb', line 643 def get_by_placeholder(text, exact: nil) wrap_impl(@impl.get_by_placeholder(unwrap_impl(text), exact: unwrap_impl(exact))) end |
#get_by_role(role, checked: nil, disabled: nil, exact: nil, expanded: nil, includeHidden: nil, level: nil, name: nil, pressed: nil, selected: nil) ⇒ Object
Allows locating elements by their [ARIA role](www.w3.org/TR/wai-aria-1.2/#roles), [ARIA attributes](www.w3.org/TR/wai-aria-1.2/#aria-attributes) and [accessible name](w3c.github.io/accname/#dfn-accessible-name).
Usage
Consider the following DOM structure.
“‘html <h3>Sign up</h3> <label>
<input type="checkbox" /> Subscribe
</label> <br/> <button>Submit</button> “‘
You can locate each element by it’s implicit role:
“‘python sync expect(page.get_by_role(“heading”, name=“Sign up”)).to_be_visible()
page.get_by_role(“checkbox”, name=“Subscribe”).check()
page.get_by_role(“button”, name=re.compile(“submit”, re.IGNORECASE)).click() “‘
Details
Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
Many html elements have an implicitly [defined role](w3c.github.io/html-aam/#html-element-role-mappings) that is recognized by the role selector. You can find all the [supported roles here](www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend** duplicating implicit roles and attributes by setting ‘role` and/or `aria-*` attributes to default values.
678 679 680 681 682 683 684 685 686 687 688 689 690 |
# File 'lib/playwright_api/page.rb', line 678 def get_by_role( role, checked: nil, disabled: nil, exact: nil, expanded: nil, includeHidden: nil, level: nil, name: nil, pressed: nil, selected: nil) wrap_impl(@impl.get_by_role(unwrap_impl(role), checked: unwrap_impl(checked), disabled: unwrap_impl(disabled), exact: unwrap_impl(exact), expanded: unwrap_impl(), includeHidden: unwrap_impl(includeHidden), level: unwrap_impl(level), name: unwrap_impl(name), pressed: unwrap_impl(pressed), selected: unwrap_impl(selected))) end |
#get_by_test_id(testId) ⇒ Object
Locate element by the test id.
Usage
Consider the following DOM structure.
“‘html <button data-testid=“directions”>Itinéraire</button> “`
You can locate the element by it’s test id:
“‘python sync page.get_by_test_id(“directions”).click() “`
Details
By default, the ‘data-testid` attribute is used as a test id. Use [`method: Selectors.setTestIdAttribute`] to configure a different test id attribute if necessary.
712 713 714 |
# File 'lib/playwright_api/page.rb', line 712 def get_by_test_id(testId) wrap_impl(@impl.get_by_test_id(unwrap_impl(testId))) end |
#get_by_text(text, exact: nil) ⇒ Object
Allows locating elements that contain given text.
See also [‘method: Locator.filter`] that allows to match by another criteria, like an accessible role, and then filter by the text content.
Usage
Consider the following DOM structure:
“‘html <div>Hello <span>world</span></div> <div>Hello</div> “`
You can locate by text substring, exact string, or a regular expression:
“‘python sync # Matches <span> page.get_by_text(“world”)
# Matches first <div> page.get_by_text(“Hello world”)
# Matches second <div> page.get_by_text(“Hello”, exact=True)
# Matches both <div>s page.get_by_text(re.compile(“Hello”))
# Matches second <div> page.get_by_text(re.compile(“^hello$”, re.IGNORECASE)) “‘
Details
Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
Input elements of the type ‘button` and `submit` are matched by their `value` instead of the text content. For example, locating by text `“Log in”` matches `<input type=button value=“Log in”>`.
754 755 756 |
# File 'lib/playwright_api/page.rb', line 754 def get_by_text(text, exact: nil) wrap_impl(@impl.get_by_text(unwrap_impl(text), exact: unwrap_impl(exact))) end |
#get_by_title(text, exact: nil) ⇒ Object
Allows locating elements by their title attribute.
Usage
Consider the following DOM structure.
“‘html <span title=’Issues count’>25 issues</span> “‘
You can check the issues count after locating it by the title text:
“‘python sync expect(page.get_by_title(“Issues count”)).to_have_text(“25 issues”) “`
774 775 776 |
# File 'lib/playwright_api/page.rb', line 774 def get_by_title(text, exact: nil) wrap_impl(@impl.get_by_title(unwrap_impl(text), exact: unwrap_impl(exact))) end |
#go_back(timeout: nil, waitUntil: nil) ⇒ Object
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If cannot go back, returns ‘null`.
Navigate to the previous page in history.
783 784 785 |
# File 'lib/playwright_api/page.rb', line 783 def go_back(timeout: nil, waitUntil: nil) wrap_impl(@impl.go_back(timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil))) end |
#go_forward(timeout: nil, waitUntil: nil) ⇒ Object
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If cannot go forward, returns ‘null`.
Navigate to the next page in history.
792 793 794 |
# File 'lib/playwright_api/page.rb', line 792 def go_forward(timeout: nil, waitUntil: nil) wrap_impl(@impl.go_forward(timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil))) end |
#goto(url, referer: nil, timeout: nil, waitUntil: nil) ⇒ Object
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first non-redirect response.
The method 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.
The method 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: The method 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).
833 834 835 |
# File 'lib/playwright_api/page.rb', line 833 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 |
#guid ⇒ Object
1814 1815 1816 |
# File 'lib/playwright_api/page.rb', line 1814 def guid wrap_impl(@impl.guid) end |
#hidden?(selector, strict: nil, timeout: nil) ⇒ Boolean
Returns whether the element is hidden, the opposite of [visible](../actionability.md#visible). ‘selector` that does not match any elements is considered hidden.
910 911 912 |
# File 'lib/playwright_api/page.rb', line 910 def hidden?(selector, strict: nil, timeout: nil) wrap_impl(@impl.hidden?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end |
#hover(selector, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ Object
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`.
When all steps combined have not finished during the specified ‘timeout`, this method throws a `TimeoutError`. Passing zero timeout disables this.
846 847 848 849 850 851 852 853 854 855 856 |
# File 'lib/playwright_api/page.rb', line 846 def hover( selector, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) wrap_impl(@impl.hover(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 |
#inner_html(selector, strict: nil, timeout: nil) ⇒ Object
Returns ‘element.innerHTML`.
860 861 862 |
# File 'lib/playwright_api/page.rb', line 860 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 |
#inner_text(selector, strict: nil, timeout: nil) ⇒ Object
Returns ‘element.innerText`.
866 867 868 |
# File 'lib/playwright_api/page.rb', line 866 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 |
#input_value(selector, strict: nil, timeout: nil) ⇒ Object
Returns ‘input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
Throws for non-input elements. However, if the element is inside the ‘<label>` element that has an associated [control](developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the control.
874 875 876 |
# File 'lib/playwright_api/page.rb', line 874 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 |
#keyboard ⇒ Object
property
56 57 58 |
# File 'lib/playwright_api/page.rb', line 56 def keyboard # property wrap_impl(@impl.keyboard) end |
#locator(selector, has: nil, hasNot: nil, hasNotText: nil, hasText: nil) ⇒ Object
The method returns an element locator that can be used to perform actions on this page / frame. 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.
[Learn more about locators](../locators.md).
925 926 927 928 929 930 931 932 |
# File 'lib/playwright_api/page.rb', line 925 def locator( selector, has: nil, hasNot: nil, hasNotText: nil, hasText: nil) wrap_impl(@impl.locator(unwrap_impl(selector), has: unwrap_impl(has), hasNot: unwrap_impl(hasNot), hasNotText: unwrap_impl(hasNotText), hasText: unwrap_impl(hasText))) end |
#main_frame ⇒ Object
The page’s main frame. Page is guaranteed to have a main frame which persists during navigations.
936 937 938 |
# File 'lib/playwright_api/page.rb', line 936 def main_frame wrap_impl(@impl.main_frame) end |
#mouse ⇒ Object
property
60 61 62 |
# File 'lib/playwright_api/page.rb', line 60 def mouse # property wrap_impl(@impl.mouse) end |
#off(event, callback) ⇒ Object
– inherited from EventEmitter –
1831 1832 1833 |
# File 'lib/playwright_api/page.rb', line 1831 def off(event, callback) event_emitter_proxy.off(event, callback) end |
#on(event, callback) ⇒ Object
– inherited from EventEmitter –
1825 1826 1827 |
# File 'lib/playwright_api/page.rb', line 1825 def on(event, callback) event_emitter_proxy.on(event, callback) end |
#once(event, callback) ⇒ Object
– inherited from EventEmitter –
1837 1838 1839 |
# File 'lib/playwright_api/page.rb', line 1837 def once(event, callback) event_emitter_proxy.once(event, callback) end |
#opener ⇒ Object
Returns the opener for popup pages and ‘null` for others. If the opener has been closed already the returns `null`.
942 943 944 |
# File 'lib/playwright_api/page.rb', line 942 def opener wrap_impl(@impl.opener) end |
#owned_context=(req) ⇒ Object
1819 1820 1821 |
# File 'lib/playwright_api/page.rb', line 1819 def owned_context=(req) wrap_impl(@impl.owned_context=(unwrap_impl(req))) end |
#pause ⇒ Object
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` option.
954 955 956 |
# File 'lib/playwright_api/page.rb', line 954 def pause wrap_impl(@impl.pause) end |
#pdf(displayHeaderFooter: nil, footerTemplate: nil, format: nil, headerTemplate: nil, height: nil, landscape: nil, margin: nil, outline: nil, pageRanges: nil, path: nil, preferCSSPageSize: nil, printBackground: nil, scale: nil, tagged: nil, width: nil) ⇒ Object
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.
Usage
“‘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(100)` - prints with width set to 100 pixels
-
‘page.pdf(’100px’)‘ - prints with width set to 100 pixels
-
‘page.pdf(’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.
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 |
# File 'lib/playwright_api/page.rb', line 1007 def pdf( displayHeaderFooter: nil, footerTemplate: nil, format: nil, headerTemplate: nil, height: nil, landscape: nil, margin: nil, outline: nil, pageRanges: nil, path: nil, preferCSSPageSize: nil, printBackground: nil, scale: nil, tagged: nil, width: nil) wrap_impl(@impl.pdf(displayHeaderFooter: unwrap_impl(), footerTemplate: unwrap_impl(), format: unwrap_impl(format), headerTemplate: unwrap_impl(headerTemplate), height: unwrap_impl(height), landscape: unwrap_impl(landscape), margin: unwrap_impl(margin), outline: unwrap_impl(outline), pageRanges: unwrap_impl(pageRanges), path: unwrap_impl(path), preferCSSPageSize: unwrap_impl(preferCSSPageSize), printBackground: unwrap_impl(printBackground), scale: unwrap_impl(scale), tagged: unwrap_impl(tagged), width: unwrap_impl(width))) end |
#press(selector, key, delay: nil, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ Object
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`, `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
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”`, `key: “Control++` 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.
Usage
“‘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() “`
1061 1062 1063 1064 1065 1066 1067 1068 1069 |
# File 'lib/playwright_api/page.rb', line 1061 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 |
#query_selector(selector, strict: nil) ⇒ Object
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: Locator.waitFor`].
1074 1075 1076 |
# File 'lib/playwright_api/page.rb', line 1074 def query_selector(selector, strict: nil) wrap_impl(@impl.query_selector(unwrap_impl(selector), strict: unwrap_impl(strict))) end |
#query_selector_all(selector) ⇒ Object
The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to ‘[]`.
1081 1082 1083 |
# File 'lib/playwright_api/page.rb', line 1081 def query_selector_all(selector) wrap_impl(@impl.query_selector_all(unwrap_impl(selector))) end |
#reload(timeout: nil, waitUntil: nil) ⇒ Object
This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
1165 1166 1167 |
# File 'lib/playwright_api/page.rb', line 1165 def reload(timeout: nil, waitUntil: nil) wrap_impl(@impl.reload(timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil))) end |
#remove_locator_handler(locator) ⇒ Object
Removes all locator handlers added by [‘method: Page.addLocatorHandler`] for a specific locator.
1157 1158 1159 |
# File 'lib/playwright_api/page.rb', line 1157 def remove_locator_handler(locator) raise NotImplementedError.new('remove_locator_handler is not implemented yet.') end |
#request ⇒ Object
API testing helper associated with this page. This method returns the same instance as
- ‘property: BrowserContext.request`
-
on the page’s context. See [‘property: BrowserContext.request`] for more details.
67 68 69 |
# File 'lib/playwright_api/page.rb', line 67 def request # property wrap_impl(@impl.request) end |
#request_gc ⇒ Object
Request the page to perform garbage collection. Note that there is no guarantee that all unreachable objects will be collected.
This is useful to help detect memory leaks. For example, if your page has a large object ‘’suspect’‘ that might be leaked, you can check that it does not leak by using a [`WeakRef`](developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef).
“‘python sync # 1. In your page, save a WeakRef for the “suspect”. page.evaluate(“globalThis.suspectWeakRef = new WeakRef(suspect)”) # 2. Request garbage collection. page.request_gc() # 3. Check that weak ref does not deref to the original object. assert page.evaluate(“!globalThis.suspectWeakRef.deref()”) “`
809 810 811 |
# File 'lib/playwright_api/page.rb', line 809 def request_gc raise NotImplementedError.new('request_gc is not implemented yet.') end |
#route(url, handler, times: nil) ⇒ Object
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.
NOTE: [‘method: Page.route`] will not intercept requests intercepted by Service Worker. See [this](github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when using request interception by setting `serviceWorkers` to `’block’‘.
NOTE: [‘method: Page.route`] will not intercept the first request of a popup page. Use [`method: BrowserContext.route`] instead.
Usage
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: 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.
1217 1218 1219 |
# File 'lib/playwright_api/page.rb', line 1217 def route(url, handler, times: nil) wrap_impl(@impl.route(unwrap_impl(url), unwrap_impl(handler), times: unwrap_impl(times))) end |
#route_from_har(har, notFound: nil, update: nil, updateContent: nil, updateMode: nil, url: nil) ⇒ Object
If specified the network requests that are made in the page will be served from the HAR file. Read more about [Replaying from HAR](../mock.md#replaying-from-har).
Playwright will not serve requests intercepted by Service Worker from the HAR file. See [this](github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when using request interception by setting ‘serviceWorkers` to `’block’‘.
1225 1226 1227 1228 1229 1230 1231 1232 1233 |
# File 'lib/playwright_api/page.rb', line 1225 def route_from_har( har, notFound: nil, update: nil, updateContent: nil, updateMode: nil, url: nil) wrap_impl(@impl.route_from_har(unwrap_impl(har), notFound: unwrap_impl(notFound), update: unwrap_impl(update), updateContent: unwrap_impl(updateContent), updateMode: unwrap_impl(updateMode), url: unwrap_impl(url))) end |
#route_web_socket(url, handler) ⇒ Object
This method allows to modify websocket connections that are made by the page.
Note that only ‘WebSocket`s created after this method was called will be routed. It is recommended to call this method before navigating the page.
Usage
Below is an example of a simple mock that responds to a single message. See ‘WebSocketRoute` for more details and examples.
“‘python sync def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
if message == "request":
ws.send("response")
def handler(ws: WebSocketRoute):
ws.(lambda message: (ws, ))
page.route_web_socket(“/ws”, handler) “‘
1254 1255 1256 |
# File 'lib/playwright_api/page.rb', line 1254 def route_web_socket(url, handler) raise NotImplementedError.new('route_web_socket is not implemented yet.') end |
#screenshot(animations: nil, caret: nil, clip: nil, fullPage: nil, mask: nil, maskColor: nil, omitBackground: nil, path: nil, quality: nil, scale: nil, style: nil, timeout: nil, type: nil) ⇒ Object
Returns the buffer with the captured screenshot.
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 |
# File 'lib/playwright_api/page.rb', line 1260 def screenshot( animations: nil, caret: nil, clip: nil, fullPage: nil, mask: nil, maskColor: nil, omitBackground: nil, path: nil, quality: nil, scale: nil, style: nil, timeout: nil, type: nil) wrap_impl(@impl.screenshot(animations: unwrap_impl(animations), caret: unwrap_impl(caret), clip: unwrap_impl(clip), fullPage: unwrap_impl(fullPage), mask: unwrap_impl(mask), maskColor: unwrap_impl(maskColor), omitBackground: unwrap_impl(omitBackground), path: unwrap_impl(path), quality: unwrap_impl(quality), scale: unwrap_impl(scale), style: unwrap_impl(style), timeout: unwrap_impl(timeout), type: unwrap_impl(type))) end |
#select_option(selector, element: nil, index: nil, value: nil, label: nil, force: nil, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ Object
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.
Usage
“‘python sync # Single selection matching the value or label 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”]) “`
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 |
# File 'lib/playwright_api/page.rb', line 1296 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 |
#set_checked(selector, checked, force: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ Object
This method checks or 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 already has the right checked state, 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.
-
Ensure that the element is now checked or 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.
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 |
# File 'lib/playwright_api/page.rb', line 1321 def set_checked( selector, checked, force: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) wrap_impl(@impl.set_checked(unwrap_impl(selector), unwrap_impl(checked), 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 |
#set_content(html, timeout: nil, waitUntil: nil) ⇒ Object Also known as: content=
This method internally calls [document.write()](developer.mozilla.org/en-US/docs/Web/API/Document/write), inheriting all its specific characteristics and behaviors.
1335 1336 1337 |
# File 'lib/playwright_api/page.rb', line 1335 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 |
#set_default_navigation_timeout(timeout) ⇒ Object Also known as:
This setting will change the default maximum navigation time for the following methods and related shortcuts:
- ‘method: Page.goBack`
- ‘method: Page.goForward`
- ‘method: Page.goto`
- ‘method: Page.reload`
- ‘method: Page.setContent`
- ‘method: Page.waitForNavigation`
- ‘method: Page.waitForURL`
NOTE: [‘method: Page.setDefaultNavigationTimeout`] takes priority over [`method: Page.setDefaultTimeout`],
- ‘method: BrowserContext.setDefaultTimeout`
-
and [‘method: BrowserContext.setDefaultNavigationTimeout`].
1352 1353 1354 |
# File 'lib/playwright_api/page.rb', line 1352 def (timeout) wrap_impl(@impl.(unwrap_impl(timeout))) end |
#set_default_timeout(timeout) ⇒ Object Also known as: default_timeout=
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`].
1361 1362 1363 |
# File 'lib/playwright_api/page.rb', line 1361 def set_default_timeout(timeout) wrap_impl(@impl.set_default_timeout(unwrap_impl(timeout))) end |
#set_extra_http_headers(headers) ⇒ Object Also known as: extra_http_headers=
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.
1370 1371 1372 |
# File 'lib/playwright_api/page.rb', line 1370 def set_extra_http_headers(headers) wrap_impl(@impl.set_extra_http_headers(unwrap_impl(headers))) end |
#set_input_files(selector, files, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ Object
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 current working directory. For empty array, clears the selected files. For inputs with a `[webkitdirectory]` attribute, only a single directory path is supported.
This method expects ‘selector` to point to an [input element](developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside the `<label>` element that has an associated [control](developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
1382 1383 1384 1385 1386 1387 1388 1389 |
# File 'lib/playwright_api/page.rb', line 1382 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 |
#set_viewport_size(viewportSize) ⇒ Object Also known as: viewport_size=
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.
- ‘method: 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. [‘method: Page.setViewportSize`] will also reset `screen` size, use [`method: Browser.newContext`] with `screen` and `viewport` parameters if you need better control of these properties.
Usage
“‘python sync page = browser.new_page() page.set_viewport_size(640, “height”: 480) page.goto(“example.com”) “`
1405 1406 1407 |
# File 'lib/playwright_api/page.rb', line 1405 def () wrap_impl(@impl.(unwrap_impl())) end |
#start_css_coverage(resetOnNavigation: nil, reportAnonymousScripts: nil) ⇒ Object
1799 1800 1801 |
# File 'lib/playwright_api/page.rb', line 1799 def start_css_coverage(resetOnNavigation: nil, reportAnonymousScripts: nil) wrap_impl(@impl.start_css_coverage(resetOnNavigation: unwrap_impl(), reportAnonymousScripts: unwrap_impl(reportAnonymousScripts))) end |
#start_js_coverage(resetOnNavigation: nil, reportAnonymousScripts: nil) ⇒ Object
1794 1795 1796 |
# File 'lib/playwright_api/page.rb', line 1794 def start_js_coverage(resetOnNavigation: nil, reportAnonymousScripts: nil) wrap_impl(@impl.start_js_coverage(resetOnNavigation: unwrap_impl(), reportAnonymousScripts: unwrap_impl(reportAnonymousScripts))) end |
#stop_css_coverage ⇒ Object
1809 1810 1811 |
# File 'lib/playwright_api/page.rb', line 1809 def stop_css_coverage wrap_impl(@impl.stop_css_coverage) end |
#stop_js_coverage ⇒ Object
1804 1805 1806 |
# File 'lib/playwright_api/page.rb', line 1804 def stop_js_coverage wrap_impl(@impl.stop_js_coverage) end |
#tap_point(selector, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ Object
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`.
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`] the method will throw if `hasTouch` option of the browser context is false.
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 |
# File 'lib/playwright_api/page.rb', line 1421 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 |
#text_content(selector, strict: nil, timeout: nil) ⇒ Object
Returns ‘element.textContent`.
1435 1436 1437 |
# File 'lib/playwright_api/page.rb', line 1435 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 |
#title ⇒ Object
Returns the page’s title.
1441 1442 1443 |
# File 'lib/playwright_api/page.rb', line 1441 def title wrap_impl(@impl.title) end |
#touchscreen ⇒ Object
property
71 72 73 |
# File 'lib/playwright_api/page.rb', line 71 def touchscreen # property wrap_impl(@impl.touchscreen) end |
#type(selector, text, delay: nil, noWaitAfter: nil, strict: nil, timeout: nil) ⇒ Object
In most cases, you should use [‘method: Locator.fill`] instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use [`method: Locator.pressSequentially`].
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`].
Usage
1454 1455 1456 1457 1458 1459 1460 1461 1462 |
# File 'lib/playwright_api/page.rb', line 1454 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 |
#uncheck(selector, force: nil, noWaitAfter: nil, position: nil, strict: nil, timeout: nil, trial: nil) ⇒ Object
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.
-
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.
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 |
# File 'lib/playwright_api/page.rb', line 1475 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 |
#unroute(url, handler: nil) ⇒ Object
Removes a route created with [‘method: Page.route`]. When `handler` is not specified, removes all routes for the `url`.
1495 1496 1497 |
# File 'lib/playwright_api/page.rb', line 1495 def unroute(url, handler: nil) wrap_impl(@impl.unroute(unwrap_impl(url), handler: unwrap_impl(handler))) end |
#unroute_all(behavior: nil) ⇒ Object
Removes all routes created with [‘method: Page.route`] and [`method: Page.routeFromHAR`].
1488 1489 1490 |
# File 'lib/playwright_api/page.rb', line 1488 def unroute_all(behavior: nil) wrap_impl(@impl.unroute_all(behavior: unwrap_impl(behavior))) end |
#url ⇒ Object
1499 1500 1501 |
# File 'lib/playwright_api/page.rb', line 1499 def url wrap_impl(@impl.url) end |
#video ⇒ Object
Video object associated with this page.
1505 1506 1507 |
# File 'lib/playwright_api/page.rb', line 1505 def video wrap_impl(@impl.video) end |
#viewport_size ⇒ Object
1509 1510 1511 |
# File 'lib/playwright_api/page.rb', line 1509 def wrap_impl(@impl.) end |
#visible?(selector, strict: nil, timeout: nil) ⇒ Boolean
Returns whether the element is [visible](../actionability.md#visible). ‘selector` that does not match any elements is considered not visible.
916 917 918 |
# File 'lib/playwright_api/page.rb', line 916 def visible?(selector, strict: nil, timeout: nil) wrap_impl(@impl.visible?(unwrap_impl(selector), strict: unwrap_impl(strict), timeout: unwrap_impl(timeout))) end |
#wait_for_event(event, predicate: nil, timeout: nil) ⇒ Object
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.
1789 1790 1791 |
# File 'lib/playwright_api/page.rb', line 1789 def wait_for_event(event, predicate: nil, timeout: nil) raise NotImplementedError.new('wait_for_event is not implemented yet.') end |
#wait_for_function(expression, arg: nil, polling: nil, timeout: nil) ⇒ Object
Returns when the ‘expression` returns a truthy value. It resolves to a JSHandle of the truthy value.
Usage
The [‘method: Page.waitForFunction`] can be used to observe viewport size change:
“‘python sync from playwright.sync_api import sync_playwright, Playwright
def run(playwright: 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) “`
1580 1581 1582 |
# File 'lib/playwright_api/page.rb', line 1580 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 |
#wait_for_load_state(state: nil, timeout: nil) ⇒ Object
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.
NOTE: Most of the time, this method is not needed because Playwright [auto-waits before every action](../actionability.md).
Usage
“‘python sync page.get_by_role(“button”).click() # click triggers navigation. page.wait_for_load_state() # the promise resolves after “load” event. “`
“‘python sync with page.expect_popup() as page_info:
page.get_by_role("button").click() # click triggers a popup.
popup = page_info.value # Wait for the “DOMContentLoaded” event. popup.wait_for_load_state(“domcontentloaded”) print(popup.title()) # popup is ready to use. “‘
1607 1608 1609 |
# File 'lib/playwright_api/page.rb', line 1607 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 |
#wait_for_selector(selector, state: nil, strict: nil, timeout: nil) ⇒ Object
Returns when element specified by selector satisfies ‘state` option. Returns `null` if waiting for `hidden` or `detached`.
NOTE: Playwright automatically waits for element to be ready before performing an action. Using ‘Locator` objects and web-first assertions makes the code wait-for-selector-free.
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.
Usage
This method works across navigations:
“‘python sync from playwright.sync_api import sync_playwright, Playwright
def run(playwright: 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)
“‘
1725 1726 1727 |
# File 'lib/playwright_api/page.rb', line 1725 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 |
#wait_for_timeout(timeout) ⇒ Object
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.
Usage
“‘python sync # wait for 1 second page.wait_for_timeout(1000) “`
1741 1742 1743 |
# File 'lib/playwright_api/page.rb', line 1741 def wait_for_timeout(timeout) wrap_impl(@impl.wait_for_timeout(unwrap_impl(timeout))) end |
#wait_for_url(url, timeout: nil, waitUntil: nil) ⇒ Object
Waits for the main frame to navigate to the given URL.
Usage
“‘python sync page.click(“a.delayed-navigation”) # clicking the link will indirectly cause a navigation page.wait_for_url(“**/target.html”) “`
1754 1755 1756 |
# File 'lib/playwright_api/page.rb', line 1754 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 |
#workers ⇒ Object
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
1779 1780 1781 |
# File 'lib/playwright_api/page.rb', line 1779 def workers wrap_impl(@impl.workers) end |