Class: Playwright::Page

Inherits:
PlaywrightApi show all
Defined in:
lib/playwright_api/page.rb

Overview

  • extends: [EventEmitter]

Page provides methods to interact with a single tab in a Browser, or an

extension background page](developer.chrome.com/extensions/background_pages) in Chromium. One [Browser

instance might have multiple [Page] instances.

This example creates a page, navigates it to a URL, and then saves a screenshot:

“‘js const { webkit } = require(’playwright’); // Or ‘chromium’ or ‘firefox’.

(async () =>

const browser = await webkit.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com');
await page.screenshot({path: 'screenshot.png');
await browser.close();

})(); “‘

“‘python async import asyncio from playwright.async_api import async_playwright

async def run(playwright):

webkit = playwright.webkit
browser = await webkit.launch()
context = await browser.new_context()
page = await context.new_page()
await page.goto("https://example.com")
await page.screenshot(path="screenshot.png")
await browser.close()

async def main():

async with async_playwright() as playwright:
    await run(playwright)

asyncio.run(main()) “‘

“‘python sync from playwright.sync_api import sync_playwright

def run(playwright):

webkit = playwright.webkit
browser = webkit.launch()
context = browser.new_context()
page = context.new_page()
page.goto("https://example.com")
page.screenshot(path="screenshot.png")
browser.close()

with sync_playwright() as playwright:

run(playwright)

“‘

The Page class emits various events (described below) which can be handled using any of Node’s native [EventEmitter](nodejs.org/api/events.html#events_class_eventemitter) methods, such as on, once or removeListener.

This example logs a message for a single page load event:

“‘js page.once(’load’, () => console.log(‘Page loaded!’)); “‘

“‘py page.once(“load”, lambda: print(“page loaded!”)) “`

To unsubscribe from events use the removeListener method:

“‘js function logRequest(interceptedRequest) {

console.log('A request was made:', interceptedRequest.url());

} page.on(‘request’, logRequest); // Sometime later… page.removeListener(‘request’, logRequest); “‘

“‘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

Methods inherited from PlaywrightApi

#==, from_channel_owner, #initialize

Constructor Details

This class inherits a constructor from Playwright::PlaywrightApi

Instance Method Details

#accessibilityObject

property



95
96
97
# File 'lib/playwright_api/page.rb', line 95

def accessibility # property
  wrap_impl(@impl.accessibility)
end

#add_init_script(script, arg: 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.

An example of overriding Math.random before the page loads:

“‘js browser // preload.js Math.random = () => 42; “`

“‘js // In your playwright script, assuming the preload.js file is in same directory await page.addInitScript({ path: ’./preload.js’ }); “‘

“‘python async # in your playwright script, assuming the preload.js file is in same directory await page.add_init_script(path=“./preload.js”) “`

“‘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.

Raises:

  • (NotImplementedError)


223
224
225
# File 'lib/playwright_api/page.rb', line 223

def add_init_script(script, arg: nil)
  raise NotImplementedError.new('add_init_script 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.

Shortcut for main frame’s [‘method: Frame.addScriptTag`].

Raises:

  • (NotImplementedError)


231
232
233
# File 'lib/playwright_api/page.rb', line 231

def add_script_tag(content: nil, path: nil, type: nil, url: nil)
  raise NotImplementedError.new('add_script_tag is not implemented yet.')
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.

Shortcut for main frame’s [‘method: Frame.addStyleTag`].

Raises:

  • (NotImplementedError)


239
240
241
# File 'lib/playwright_api/page.rb', line 239

def add_style_tag(content: nil, path: nil, url: nil)
  raise NotImplementedError.new('add_style_tag is not implemented yet.')
end

#after_initializeObject



1850
1851
1852
# File 'lib/playwright_api/page.rb', line 1850

def after_initialize
  wrap_impl(@impl.after_initialize)
end

#bring_to_frontObject

Brings page to front (activates tab).

Raises:

  • (NotImplementedError)


244
245
246
# File 'lib/playwright_api/page.rb', line 244

def bring_to_front
  raise NotImplementedError.new('bring_to_front is not implemented yet.')
end

#check(selector, force: nil, noWaitAfter: nil, timeout: nil) ⇒ Object

This method checks an element matching selector by performing the following steps:

  1. Find an element match matching selector. If there is none, wait until a matching element is attached to the DOM.

  2. Ensure that matched element is a checkbox or a radio input. If not, this method rejects. If the element is already checked, this method returns immediately.

  3. 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.

  4. Scroll the element into view if needed.

  5. Use [‘property: Page.mouse`] to click in the center of the element.

  6. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

  7. Ensure that the element is now checked. If not, this method rejects.

When all steps combined have not finished during the specified timeout, this method rejects with a TimeoutError. Passing zero timeout disables this.

Shortcut for main frame’s [‘method: Frame.check`].

Raises:

  • (NotImplementedError)


263
264
265
# File 'lib/playwright_api/page.rb', line 263

def check(selector, force: nil, noWaitAfter: nil, timeout: nil)
  raise NotImplementedError.new('check is not implemented yet.')
end

#checked?(selector, timeout: nil) ⇒ Boolean

Returns whether the element is checked. Throws if the element is not a checkbox or radio input.

Returns:

  • (Boolean)

Raises:

  • (NotImplementedError)


985
986
987
# File 'lib/playwright_api/page.rb', line 985

def checked?(selector, timeout: nil)
  raise NotImplementedError.new('checked? is not implemented yet.')
end

#click(selector, button: nil, clickCount: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) ⇒ Object

This method clicks an element matching selector by performing the following steps:

  1. Find an element match matching selector. If there is none, wait until a matching element is attached to the DOM.

  2. 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.

  3. Scroll the element into view if needed.

  4. Use [‘property: Page.mouse`] to click in the center of the element, or the specified position.

  5. 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 rejects with a TimeoutError. Passing zero timeout disables this.

Shortcut for main frame’s [‘method: Frame.click`].



279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/playwright_api/page.rb', line 279

def click(
      selector,
      button: nil,
      clickCount: nil,
      delay: nil,
      force: nil,
      modifiers: nil,
      noWaitAfter: nil,
      position: nil,
      timeout: nil)
  wrap_impl(@impl.click(selector, button: button, clickCount: clickCount, delay: delay, force: force, modifiers: modifiers, noWaitAfter: noWaitAfter, position: position, timeout: timeout))
end

#close(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.



299
300
301
# File 'lib/playwright_api/page.rb', line 299

def close(runBeforeUnload: nil)
  wrap_impl(@impl.close(runBeforeUnload: runBeforeUnload))
end

#closed?Boolean

Indicates that the page has been closed.

Returns:

  • (Boolean)


990
991
992
# File 'lib/playwright_api/page.rb', line 990

def closed?
  wrap_impl(@impl.closed?)
end

#contentObject

Gets the full HTML contents of the page, including the doctype.



304
305
306
# File 'lib/playwright_api/page.rb', line 304

def content
  wrap_impl(@impl.content)
end

#contextObject

Get the browser context that the page belongs to.



309
310
311
# File 'lib/playwright_api/page.rb', line 309

def context
  wrap_impl(@impl.context)
end

#coverageObject

Browser-specific Coverage implementation, only available for Chromium atm. See ChromiumCoverage(#class-chromiumcoverage) for more details.

Raises:

  • (NotImplementedError)


101
102
103
# File 'lib/playwright_api/page.rb', line 101

def coverage # property
  raise NotImplementedError.new('coverage is not implemented yet.')
end

#dblclick(selector, button: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) ⇒ Object

This method double clicks an element matching selector by performing the following steps:

  1. Find an element match matching selector. If there is none, wait until a matching element is attached to the DOM.

  2. 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.

  3. Scroll the element into view if needed.

  4. Use [‘property: Page.mouse`] to double click in the center of the element, or the specified position.

  5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set. Note that if the first click of the ‘dblclick()` triggers a navigation event, this method will reject.

When all steps combined have not finished during the specified timeout, this method rejects with a TimeoutError. Passing zero timeout disables this.

> NOTE: ‘page.dblclick()` dispatches two click events and a single dblclick event.

Shortcut for main frame’s [‘method: Frame.dblclick`].

Raises:

  • (NotImplementedError)


328
329
330
331
332
333
334
335
336
337
338
# File 'lib/playwright_api/page.rb', line 328

def dblclick(
      selector,
      button: nil,
      delay: nil,
      force: nil,
      modifiers: nil,
      noWaitAfter: nil,
      position: nil,
      timeout: nil)
  raise NotImplementedError.new('dblclick is not implemented yet.')
end

#disabled?(selector, timeout: nil) ⇒ Boolean

Returns whether the element is disabled, the opposite of [enabled](./actionability.md#enabled).

Returns:

  • (Boolean)

Raises:

  • (NotImplementedError)


995
996
997
# File 'lib/playwright_api/page.rb', line 995

def disabled?(selector, timeout: nil)
  raise NotImplementedError.new('disabled? is not implemented yet.')
end

#dispatch_event(selector, type, eventInit: nil, timeout: nil) ⇒ Object

The snippet below dispatches the click event on the element. Regardless of the visibility state of the elment, click is dispatched. This is equivalend to calling [element.click()](developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).

“‘js await page.dispatchEvent(’button#submit’, ‘click’); “‘

“‘python async await page.dispatch_event(“button#submit”, “click”) “`

“‘python sync page.dispatch_event(“button#submit”, “click”) “`

Under the hood, it creates an instance of an event based on the given type, initializes it with eventInit properties and dispatches it on the element. Events are composed, cancelable and bubble by default.

Since eventInit is event-specific, please refer to the events documentation for the lists of initial properties:

You can also specify JSHandle as the property value if you want live objects to be passed into the event:

“‘js // Note you can only create DataTransfer in Chromium and Firefox const dataTransfer = await page.evaluateHandle(() => new DataTransfer()); await page.dispatchEvent(’#source’, ‘dragstart’, { dataTransfer }); “‘

“‘python async # note you can only create data_transfer in chromium and firefox data_transfer = await page.evaluate_handle(“new DataTransfer()”) await page.dispatch_event(“#source”, “dragstart”, { “dataTransfer”: data_transfer }) “`

“‘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 }) “`

Raises:

  • (NotImplementedError)


389
390
391
# File 'lib/playwright_api/page.rb', line 389

def dispatch_event(selector, type, eventInit: nil, timeout: nil)
  raise NotImplementedError.new('dispatch_event is not implemented yet.')
end

#editable?(selector, timeout: nil) ⇒ Boolean

Returns whether the element is [editable](./actionability.md#editable).

Returns:

  • (Boolean)

Raises:

  • (NotImplementedError)


1000
1001
1002
# File 'lib/playwright_api/page.rb', line 1000

def editable?(selector, timeout: nil)
  raise NotImplementedError.new('editable? is not implemented yet.')
end

#emulate_media(params) ⇒ Object

“‘js await page.evaluate(() => matchMedia(’screen’).matches); // → true await page.evaluate(() => matchMedia(‘print’).matches); // → false

await page.emulateMedia({ media: ‘print’ }); await page.evaluate(() => matchMedia(‘screen’).matches); // → false await page.evaluate(() => matchMedia(‘print’).matches); // → true

await page.emulateMedia({}); await page.evaluate(() => matchMedia(‘screen’).matches); // → true await page.evaluate(() => matchMedia(‘print’).matches); // → false “‘

“‘python async await page.evaluate(“matchMedia(’screen’).matches”) # → True await page.evaluate(“matchMedia(‘print’).matches”) # → False

await page.emulate_media(media=“print”) await page.evaluate(“matchMedia(‘screen’).matches”) # → False await page.evaluate(“matchMedia(‘print’).matches”) # → True

await page.emulate_media() await page.evaluate(“matchMedia(‘screen’).matches”) # → True await page.evaluate(“matchMedia(‘print’).matches”) # → False “‘

“‘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 “‘

“‘js await page.emulateMedia({ colorScheme: ’dark’ }); await page.evaluate(() => matchMedia(‘(prefers-color-scheme: dark)’).matches); // → true await page.evaluate(() => matchMedia(‘(prefers-color-scheme: light)’).matches); // → false await page.evaluate(() => matchMedia(‘(prefers-color-scheme: no-preference)’).matches); // → false “‘

“‘python async await page.emulate_media(color_scheme=“dark”) await page.evaluate(“matchMedia(’(prefers-color-scheme: dark)‘).matches”) # → True await page.evaluate(“matchMedia(’(prefers-color-scheme: light)‘).matches”) # → False await page.evaluate(“matchMedia(’(prefers-color-scheme: no-preference)‘).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”) “`

Raises:

  • (NotImplementedError)


481
482
483
# File 'lib/playwright_api/page.rb', line 481

def emulate_media(params)
  raise NotImplementedError.new('emulate_media is not implemented yet.')
end

#enabled?(selector, timeout: nil) ⇒ Boolean

Returns whether the element is [enabled](./actionability.md#enabled).

Returns:

  • (Boolean)

Raises:

  • (NotImplementedError)


1005
1006
1007
# File 'lib/playwright_api/page.rb', line 1005

def enabled?(selector, timeout: nil)
  raise NotImplementedError.new('enabled? is not implemented yet.')
end

#eval_on_selector(selector, pageFunction, arg: nil) ⇒ Object

The method finds an element matching the specified selector within the page and passes it as a first argument to pageFunction. If no elements match the selector, the method throws an error. Returns the value of pageFunction.

If pageFunction returns a [Promise], then [‘method: Page.$eval`] would wait for the promise to resolve and return its value.

Examples:

“‘js const searchValue = await page.$eval(’#search’, el => el.value); const preloadHref = await page.$eval(‘link’, el => el.href); const html = await page.$eval(‘.main-container’, (e, suffix) => e.outerHTML + suffix, ‘hello’); “‘

“‘python async search_value = await page.eval_on_selector(“#search”, “el => el.value”) preload_href = await page.eval_on_selector(“link“, ”el => el.href“) html = await page.eval_on_selector(”.main-container“, ”(e, suffix) => e.outer_html + suffix“, ”hello“) “`

“‘python sync search_value = page.eval_on_selector(“#search”, “el => el.value”) preload_href = page.eval_on_selector(“link“, ”el => el.href“) html = page.eval_on_selector(”.main-container“, ”(e, suffix) => e.outer_html + suffix“, ”hello“) “`

Shortcut for main frame’s [‘method: Frame.$eval`].



161
162
163
# File 'lib/playwright_api/page.rb', line 161

def eval_on_selector(selector, pageFunction, arg: nil)
  wrap_impl(@impl.eval_on_selector(selector, pageFunction, arg: arg))
end

#eval_on_selector_all(selector, pageFunction, 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 pageFunction. Returns the result of pageFunction invocation.

If pageFunction returns a [Promise], then [‘method: Page.$$eval`] would wait for the promise to resolve and return its value.

Examples:

“‘js const divCounts = await page.$$eval(’div’, (divs, min) => divs.length >= min, 10); “‘

“‘python async div_counts = await page.eval_on_selector_all(“div”, “(divs, min) => divs.length >= min”, 10) “`

“‘python sync div_counts = page.eval_on_selector_all(“div”, “(divs, min) => divs.length >= min”, 10) “`



185
186
187
# File 'lib/playwright_api/page.rb', line 185

def eval_on_selector_all(selector, pageFunction, arg: nil)
  wrap_impl(@impl.eval_on_selector_all(selector, pageFunction, arg: arg))
end

#evaluate(pageFunction, arg: nil) ⇒ Object

Returns the value of the pageFunction 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. DevTools Protocol also supports transferring some additional values that are not serializable by JSON: -0, NaN, Infinity, -Infinity, and bigint literals.

Passing argument to pageFunction:

“‘js const result = await page.evaluate(([x, y]) =>

return Promise.resolve(x * y);

, [7, 8]); console.log(result); // prints “56” “‘

“‘python async result = await page.evaluate(“([x, y]) => Promise.resolve(x * y)”, [7, 8]) print(result) # prints “56” “`

“‘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:

“‘js console.log(await page.evaluate(’1 + 2’)); // prints “3” const x = 10; console.log(await page.evaluate(‘1 + $x`)); // prints “11” “`

“‘python async print(await page.evaluate(“1 + 2”)) # prints “3” x = 10 print(await page.evaluate(f“1 + x”)) # prints “11” “`

“‘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`]:

“‘js const bodyHandle = await page.$(’body’); const html = await page.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, ‘hello’]); await bodyHandle.dispose(); “‘

“‘python async body_handle = await page.query_selector(“body”) html = await page.evaluate(“([body, suffix]) => body.innerHTML + suffix”, [body_handle, “hello”]) await body_handle.dispose() “`

“‘python sync body_handle = page.query_selector(“body”) html = page.evaluate(“([body, suffix]) => body.innerHTML + suffix”, [body_handle, “hello”]) body_handle.dispose() “`

Shortcut for main frame’s [‘method: Frame.evaluate`].



557
558
559
# File 'lib/playwright_api/page.rb', line 557

def evaluate(pageFunction, arg: nil)
  wrap_impl(@impl.evaluate(pageFunction, arg: arg))
end

#evaluate_handle(pageFunction, arg: nil) ⇒ Object

Returns the value of the pageFunction invocation as in-page object (JSHandle).

The only difference between [‘method: Page.evaluate`] and [`method: Page.evaluateHandle`] is that

‘method: Page.evaluateHandle`

returns in-page object (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.

“‘js const aWindowHandle = await page.evaluateHandle(() => Promise.resolve(window)); aWindowHandle; // Handle for the window object. “`

“‘python async # FIXME a_window_handle = await page.evaluate_handle(“Promise.resolve(window)”) a_window_handle # handle for the window object. “`

“‘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:

“‘js const aHandle = await page.evaluateHandle(’document’); // Handle for the ‘document’ “‘

“‘python async a_handle = await page.evaluate_handle(“document”) # handle for the “document” “`

“‘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`]:

“‘js const aHandle = await page.evaluateHandle(() => document.body); const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle); console.log(await resultHandle.jsonValue()); await resultHandle.dispose(); “`

“‘python async a_handle = await page.evaluate_handle(“document.body”) result_handle = await page.evaluate_handle(“body => body.innerHTML”, a_handle) print(await result_handle.json_value()) await result_handle.dispose() “`

“‘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() “`



624
625
626
# File 'lib/playwright_api/page.rb', line 624

def evaluate_handle(pageFunction, arg: nil)
  wrap_impl(@impl.evaluate_handle(pageFunction, arg: arg))
end

#expect_event(event, optionsOrPredicate: nil) ⇒ 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.

“‘js const [frame, _] = await Promise.all([

page.waitForEvent('framenavigated'),
page.click('button')

]); “‘

“‘python async async with page.expect_event(“framenavigated”) as event_info:

await page.click("button")

frame = await event_info.value “‘

“‘python sync with page.expect_event(“framenavigated”) as event_info:

page.click("button")

frame = event_info.value “‘

Raises:

  • (NotImplementedError)


1496
1497
1498
# File 'lib/playwright_api/page.rb', line 1496

def expect_event(event, optionsOrPredicate: nil)
  raise NotImplementedError.new('expect_event is not implemented yet.')
end

#expect_navigation(timeout: nil, url: nil, waitUntil: nil) ⇒ Object

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.

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:

“‘js const [response] = await Promise.all([

page.waitForNavigation(), // The promise resolves after navigation has finished
page.click('a.delayed-navigation'), // Clicking the link will indirectly cause a navigation

]); “‘

“‘python async async with page.expect_navigation():

await page.click("a.delayed-navigation") # clicking the link will indirectly cause a navigation

# Resolves after navigation has finished “‘

“‘python sync with page.expect_navigation():

page.click("a.delayed-navigation") # clicking the link will indirectly cause a navigation

# 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.

Shortcut for main frame’s [‘method: Frame.waitForNavigation`].

Raises:

  • (NotImplementedError)


1660
1661
1662
# File 'lib/playwright_api/page.rb', line 1660

def expect_navigation(timeout: nil, url: nil, waitUntil: nil)
  raise NotImplementedError.new('expect_navigation is not implemented yet.')
end

#expect_request(urlOrPredicate, timeout: nil) ⇒ Object

Waits for the matching request and returns it.

“‘js const firstRequest = await page.waitForRequest(’example.com/resource’); const finalRequest = await page.waitForRequest(request => request.url() === ‘example.com’ && request.method() === ‘GET’); return firstRequest.url(); “‘

“‘python async async with page.expect_request(“example.com/resource”) as first:

await page.click('button')

first_request = await first.value

async with page.expect_request(lambda request: request.url == “example.com” and request.method == “get”) as second:

await page.click('img')

second_request = await second.value “‘

“‘python sync with page.expect_request(“example.com/resource”) as first:

page.click('button')

first_request = first.value

with page.expect_request(lambda request: request.url == “example.com” and request.method == “get”) as second:

page.click('img')

second_request = second.value “‘

“‘js await page.waitForRequest(request => request.url().searchParams.get(’foo’) === ‘bar’ && request.url().searchParams.get(‘foo2’) === ‘bar2’); “‘

Raises:

  • (NotImplementedError)


1697
1698
1699
# File 'lib/playwright_api/page.rb', line 1697

def expect_request(urlOrPredicate, timeout: nil)
  raise NotImplementedError.new('expect_request is not implemented yet.')
end

#expect_response(urlOrPredicate, timeout: nil) ⇒ Object

Returns the matched response.

“‘js const firstResponse = await page.waitForResponse(’example.com/resource’); const finalResponse = await page.waitForResponse(response => response.url() === ‘example.com’ && response.status() === 200); return finalResponse.ok(); “‘

“‘python async first_response = await page.wait_for_response(“example.com/resource”) final_response = await page.wait_for_response(lambda response: response.url == “example.com” and response.status === 200) return final_response.ok “`

“‘python sync first_response = page.wait_for_response(“example.com/resource”) final_response = page.wait_for_response(lambda response: response.url == “example.com” and response.status === 200) return final_response.ok “`

Raises:

  • (NotImplementedError)


1721
1722
1723
# File 'lib/playwright_api/page.rb', line 1721

def expect_response(urlOrPredicate, timeout: nil)
  raise NotImplementedError.new('expect_response is not implemented yet.')
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.

An example of exposing page URL to all frames in a page:

“‘js const { webkit } = require(’playwright’); // Or ‘chromium’ or ‘firefox’.

(async () => {

const browser = await webkit.launch({ headless: false });
const context = await browser.newContext();
const page = await context.newPage();
await page.exposeBinding('pageURL', ({ page }) => page.url());
await page.setContent(`
  <script>
    async function onClick() {
      document.querySelector('div').textContent = await window.pageURL();
    }
  </script>
  <button onclick="onClick()">Click me</button>
  <div></div>
`);
await page.click('button');

})(); “‘

“‘python async import asyncio from playwright.async_api import async_playwright

async def run(playwright):

webkit = playwright.webkit
browser = await webkit.launch(headless=false)
context = await browser.new_context()
page = await context.new_page()
await page.expose_binding("pageURL", lambda source: source["page"].url)
await page.set_content("""
<script>
  async function onClick() {
    document.querySelector('div').textContent = await window.pageURL();
  }
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
await page.click("button")

async def main():

async with async_playwright() as playwright:
    await run(playwright)

asyncio.run(main()) “‘

“‘python sync from playwright.sync_api import sync_playwright

def run(playwright):

webkit = playwright.webkit
browser = webkit.launch(headless=false)
context = browser.new_context()
page = context.new_page()
page.expose_binding("pageURL", lambda source: source["page"].url)
page.set_content("""
<script>
  async function onClick() {
    document.querySelector('div').textContent = await window.pageURL();
  }
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
page.click("button")

with sync_playwright() as playwright:

run(playwright)

“‘

An example of passing an element handle:

“‘js await page.exposeBinding(’clicked’, async (source, element) =>

console.log(await element.textContent());

, { handle: true }); await page.setContent(‘

<script>
  document.addEventListener('click', event => window.clicked(event.target));
</script>
<div>Click me</div>
<div>Or click me</div>

‘); “`

“‘python async async def print(source, element):

print(await element.text_content())

await page.expose_binding(“clicked”, print, handle=true) await page.set_content(“”“

<script>
  document.addEventListener('click', event => window.clicked(event.target));
</script>
<div>Click me</div>
<div>Or click me</div>

“”“) “‘

“‘python sync def print(source, element):

print(element.text_content())

page.expose_binding(“clicked”, print, handle=true) page.set_content(“”“

<script>
  document.addEventListener('click', event => window.clicked(event.target));
</script>
<div>Click me</div>
<div>Or click me</div>

“”“) “‘

Raises:

  • (NotImplementedError)


757
758
759
# File 'lib/playwright_api/page.rb', line 757

def expose_binding(name, callback, handle: nil)
  raise NotImplementedError.new('expose_binding is not implemented yet.')
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.

An example of adding an sha1 function to the page:

“‘js const { webkit } = require(’playwright’); // Or ‘chromium’ or ‘firefox’. const crypto = require(‘crypto’);

(async () => {

const browser = await webkit.launch({ headless: false });
const page = await browser.newPage();
await page.exposeFunction('sha1', text => crypto.createHash('sha1').update(text).digest('hex'));
await page.setContent(`
  <script>
    async function onClick() {
      document.querySelector('div').textContent = await window.sha1('PLAYWRIGHT');
    }
  </script>
  <button onclick="onClick()">Click me</button>
  <div></div>
`);
await page.click('button');

})(); “‘

“‘python async import asyncio import hashlib from playwright.async_api import async_playwright

async def sha1(text):

m = hashlib.sha1()
m.update(bytes(text, "utf8"))
return m.hexdigest()

async def run(playwright):

webkit = playwright.webkit
browser = await webkit.launch(headless=False)
page = await browser.new_page()
await page.expose_function("sha1", sha1)
await page.set_content("""
    <script>
      async function onClick() {
        document.querySelector('div').textContent = await window.sha1('PLAYWRIGHT');
      }
    </script>
    <button onclick="onClick()">Click me</button>
    <div></div>
""")
await page.click("button")

async def main():

async with async_playwright() as playwright:
    await run(playwright)

asyncio.run(main()) “‘

“‘python sync import hashlib from playwright.sync_api import sync_playwright

def sha1(text):

m = hashlib.sha1()
m.update(bytes(text, "utf8"))
return m.hexdigest()

def run(playwright):

webkit = playwright.webkit
browser = webkit.launch(headless=False)
page = browser.new_page()
page.expose_function("sha1", sha1)
page.set_content("""
    <script>
      async function onClick() {
        document.querySelector('div').textContent = await window.sha1('PLAYWRIGHT');
      }
    </script>
    <button onclick="onClick()">Click me</button>
    <div></div>
""")
page.click("button")

with sync_playwright() as playwright:

run(playwright)

“‘

Raises:

  • (NotImplementedError)


856
857
858
# File 'lib/playwright_api/page.rb', line 856

def expose_function(name, callback)
  raise NotImplementedError.new('expose_function is not implemented yet.')
end

#fill(selector, value, noWaitAfter: 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. If the element matching selector is not an ‘<input>`, `<textarea>` or [contenteditable] element, this method throws an error. Note that you can pass an empty string to clear the input field.

To send fine-grained keyboard events, use [‘method: Page.type`].

Shortcut for main frame’s [‘method: Frame.fill`]

Raises:

  • (NotImplementedError)


868
869
870
# File 'lib/playwright_api/page.rb', line 868

def fill(selector, value, noWaitAfter: nil, timeout: nil)
  raise NotImplementedError.new('fill is not implemented yet.')
end

#focus(selector, 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.

Shortcut for main frame’s [‘method: Frame.focus`].



876
877
878
# File 'lib/playwright_api/page.rb', line 876

def focus(selector, timeout: nil)
  wrap_impl(@impl.focus(selector, timeout: timeout))
end

#frame(frameSelector) ⇒ Object

Returns frame matching the specified criteria. Either name or url must be specified.

“‘js const frame = page.frame(’frame-name’); “‘

“‘py frame = page.frame(name=“frame-name”) “`

“‘js const frame = page.frame({ url: /.domain./ }); “`

“‘py frame = page.frame(url=r“.domain.”) “`



899
900
901
# File 'lib/playwright_api/page.rb', line 899

def frame(frameSelector)
  wrap_impl(@impl.frame(frameSelector))
end

#framesObject

An array of all frames attached to the page.



904
905
906
# File 'lib/playwright_api/page.rb', line 904

def frames
  wrap_impl(@impl.frames)
end

#get_attribute(selector, name, timeout: nil) ⇒ Object

Returns element attribute value.

Raises:

  • (NotImplementedError)


909
910
911
# File 'lib/playwright_api/page.rb', line 909

def get_attribute(selector, name, timeout: nil)
  raise NotImplementedError.new('get_attribute is not implemented yet.')
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 can not go back, returns null.

Navigate to the previous page in history.

Raises:

  • (NotImplementedError)


917
918
919
# File 'lib/playwright_api/page.rb', line 917

def go_back(timeout: nil, waitUntil: nil)
  raise NotImplementedError.new('go_back is not implemented yet.')
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 can not go forward, returns null.

Navigate to the next page in history.

Raises:

  • (NotImplementedError)


925
926
927
# File 'lib/playwright_api/page.rb', line 925

def go_forward(timeout: nil, waitUntil: nil)
  raise NotImplementedError.new('go_forward is not implemented yet.')
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 response of the last redirect.

page.goto will throw an error if:

  • there’s an SSL error (e.g. in case of self-signed certificates).

  • target URL is invalid.

  • the timeout is exceeded during navigation.

  • the remote server does not respond or is unreachable.

  • the main resource failed to load.

page.goto will not throw an error when any valid HTTP status code is returned by the remote server, including 404 “Not Found” and 500 “Internal Server Error”. The status code for such responses can be retrieved by calling [‘method: Response.status`].

> NOTE: page.goto either throws an error or returns a main resource response. The only exceptions are navigation to about:blank or navigation to the same URL with a different hash, which would succeed and return null. > NOTE: Headless mode doesn’t support navigation to a PDF document. See the [upstream issue](bugs.chromium.org/p/chromium/issues/detail?id=761295).

Shortcut for main frame’s [‘method: Frame.goto`]



949
950
951
# File 'lib/playwright_api/page.rb', line 949

def goto(url, referer: nil, timeout: nil, waitUntil: nil)
  wrap_impl(@impl.goto(url, referer: referer, timeout: timeout, waitUntil: waitUntil))
end

#hidden?(selector, timeout: nil) ⇒ Boolean

Returns whether the element is hidden, the opposite of [visible](./actionability.md#visible).

Returns:

  • (Boolean)

Raises:

  • (NotImplementedError)


1010
1011
1012
# File 'lib/playwright_api/page.rb', line 1010

def hidden?(selector, timeout: nil)
  raise NotImplementedError.new('hidden? is not implemented yet.')
end

#hover(selector, force: nil, modifiers: nil, position: nil, timeout: nil) ⇒ Object

This method hovers over an element matching selector by performing the following steps:

  1. Find an element match matching selector. If there is none, wait until a matching element is attached to the DOM.

  2. 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.

  3. Scroll the element into view if needed.

  4. Use [‘property: Page.mouse`] to hover over the center of the element, or the specified position.

  5. 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 rejects with a TimeoutError. Passing zero timeout disables this.

Shortcut for main frame’s [‘method: Frame.hover`].

Raises:

  • (NotImplementedError)


965
966
967
968
969
970
971
972
# File 'lib/playwright_api/page.rb', line 965

def hover(
      selector,
      force: nil,
      modifiers: nil,
      position: nil,
      timeout: nil)
  raise NotImplementedError.new('hover is not implemented yet.')
end

#inner_html(selector, timeout: nil) ⇒ Object

Returns element.innerHTML.

Raises:

  • (NotImplementedError)


975
976
977
# File 'lib/playwright_api/page.rb', line 975

def inner_html(selector, timeout: nil)
  raise NotImplementedError.new('inner_html is not implemented yet.')
end

#inner_text(selector, timeout: nil) ⇒ Object

Returns element.innerText.

Raises:

  • (NotImplementedError)


980
981
982
# File 'lib/playwright_api/page.rb', line 980

def inner_text(selector, timeout: nil)
  raise NotImplementedError.new('inner_text is not implemented yet.')
end

#keyboardObject

property



105
106
107
# File 'lib/playwright_api/page.rb', line 105

def keyboard # property
  wrap_impl(@impl.keyboard)
end

#main_frameObject

The page’s main frame. Page is guaranteed to have a main frame which persists during navigations.



1020
1021
1022
# File 'lib/playwright_api/page.rb', line 1020

def main_frame
  wrap_impl(@impl.main_frame)
end

#mouseObject

property



109
110
111
# File 'lib/playwright_api/page.rb', line 109

def mouse # property
  wrap_impl(@impl.mouse)
end

#off(event, callback) ⇒ Object

– inherited from EventEmitter –



1862
1863
1864
# File 'lib/playwright_api/page.rb', line 1862

def off(event, callback)
  wrap_impl(@impl.off(event, callback))
end

#on(event, callback) ⇒ Object

– inherited from EventEmitter –



1856
1857
1858
# File 'lib/playwright_api/page.rb', line 1856

def on(event, callback)
  wrap_impl(@impl.on(event, callback))
end

#once(event, callback) ⇒ Object

– inherited from EventEmitter –



1868
1869
1870
# File 'lib/playwright_api/page.rb', line 1868

def once(event, callback)
  wrap_impl(@impl.once(event, callback))
end

#openerObject

Returns the opener for popup pages and null for others. If the opener has been closed already the returns null.



1025
1026
1027
# File 'lib/playwright_api/page.rb', line 1025

def opener
  wrap_impl(@impl.opener)
end

#owned_context=(req) ⇒ Object



1825
1826
1827
# File 'lib/playwright_api/page.rb', line 1825

def owned_context=(req)
  wrap_impl(@impl.owned_context=(req))
end

#pdf(displayHeaderFooter: nil, footerTemplate: nil, format: nil, headerTemplate: nil, height: nil, landscape: nil, margin: nil, pageRanges: nil, path: nil, preferCSSPageSize: nil, printBackground: nil, scale: nil, width: nil) ⇒ 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.

“‘js // Generates a PDF with ’screen’ media type. await page.emulateMedia(‘screen’); await page.pdf(‘page.pdf’); “‘

“‘python async # generates a pdf with “screen” media type. await page.emulate_media(media=“screen”) await page.pdf(path=“page.pdf”) “`

“‘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.

Raises:

  • (NotImplementedError)


1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
# File 'lib/playwright_api/page.rb', line 1087

def pdf(
      displayHeaderFooter: nil,
      footerTemplate: nil,
      format: nil,
      headerTemplate: nil,
      height: nil,
      landscape: nil,
      margin: nil,
      pageRanges: nil,
      path: nil,
      preferCSSPageSize: nil,
      printBackground: nil,
      scale: nil,
      width: nil)
  raise NotImplementedError.new('pdf is not implemented yet.')
end

#press(selector, key, delay: nil, noWaitAfter: 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.

Holding down Shift will type the text that corresponds to the key in the upper case.

If key is a single character, it is case-sensitive, so the values a and A will generate different respective texts.

Shortcuts such as ‘key: “Control+o”` or `key: “Control+Shift+T”` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.

“‘js const page = await browser.newPage(); await page.goto(’keycode.info’); await page.press(‘body’, ‘A’); await page.screenshot({ path: ‘A.png’ }); await page.press(‘body’, ‘ArrowLeft’); await page.screenshot({ path: ‘ArrowLeft.png’ }); await page.press(‘body’, ‘Shift+O’); await page.screenshot({ path: ‘O.png’ }); await browser.close(); “‘

“‘python async page = await browser.new_page() await page.goto(“keycode.info”) await page.press(“body”, “A”) await page.screenshot(path=“a.png”) await page.press(“body”, “ArrowLeft”) await page.screenshot(path=“arrow_left.png”) await page.press(“body”, “Shift+O”) await page.screenshot(path=“o.png”) await browser.close() “`

“‘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() “`



1159
1160
1161
1162
1163
1164
1165
1166
# File 'lib/playwright_api/page.rb', line 1159

def press(
      selector,
      key,
      delay: nil,
      noWaitAfter: nil,
      timeout: nil)
  wrap_impl(@impl.press(selector, key, delay: delay, noWaitAfter: noWaitAfter, timeout: timeout))
end

#query_selector(selector) ⇒ 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.

Shortcut for main frame’s [‘method: Frame.$`].



121
122
123
# File 'lib/playwright_api/page.rb', line 121

def query_selector(selector)
  wrap_impl(@impl.query_selector(selector))
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 [].

Shortcut for main frame’s [‘method: Frame.$$`].



129
130
131
# File 'lib/playwright_api/page.rb', line 129

def query_selector_all(selector)
  wrap_impl(@impl.query_selector_all(selector))
end

#reload(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.

Raises:

  • (NotImplementedError)


1170
1171
1172
# File 'lib/playwright_api/page.rb', line 1170

def reload(timeout: nil, waitUntil: nil)
  raise NotImplementedError.new('reload is not implemented yet.')
end

#route(url, handler) ⇒ 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.

An example of a naïve handler that aborts all image requests:

“‘js const page = await browser.newPage(); await page.route(’*/.png,jpg,jpeg‘, route => route.abort()); await page.goto(’example.com’); await browser.close(); “‘

“‘python async page = await browser.new_page() await page.route(“*/.png,jpg,jpeg”, lambda route: route.abort()) await page.goto(“example.com”) await browser.close() “`

“‘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:

“‘js const page = await browser.newPage(); await page.route(/(.png$)|(.jpg$)/, route => route.abort()); await page.goto(’example.com’); await browser.close(); “‘

“‘python async page = await browser.new_page() await page.route(re.compile(r“(.png$)|(.jpg$)”), lambda route: route.abort()) await page.goto(“example.com”) await browser.close() “`

“‘python sync page = browser.new_page() page.route(re.compile(r“(.png$)|(.jpg$)”), lambda route: route.abort()) page.goto(“example.com”) browser.close() “`

Page routes take precedence over browser context routes (set up with [‘method: BrowserContext.route`]) when request matches both handlers.

> NOTE: Enabling routing disables http cache.

Raises:

  • (NotImplementedError)


1232
1233
1234
# File 'lib/playwright_api/page.rb', line 1232

def route(url, handler)
  raise NotImplementedError.new('route is not implemented yet.')
end

#screenshot(clip: nil, fullPage: nil, omitBackground: nil, path: nil, quality: nil, timeout: nil, type: nil) ⇒ Object

Returns the buffer with the captured screenshot.

> NOTE: Screenshots take at least 1/6 second on Chromium OS X and Chromium Windows. See crbug.com/741689 for discussion.



1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
# File 'lib/playwright_api/page.rb', line 1240

def screenshot(
      clip: nil,
      fullPage: nil,
      omitBackground: nil,
      path: nil,
      quality: nil,
      timeout: nil,
      type: nil)
  wrap_impl(@impl.screenshot(clip: clip, fullPage: fullPage, omitBackground: omitBackground, path: path, quality: quality, timeout: timeout, type: type))
end

#select_option(selector, values, noWaitAfter: nil, timeout: nil) ⇒ Object

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. If there’s no ‘<select>` element matching selector, the method throws an error.

Will wait until all specified options are present in the ‘<select>` element.

“‘js // single selection matching the value page.selectOption(’select#colors’, ‘blue’);

// single selection matching the label page.selectOption(‘select#colors’, { label: ‘Blue’ });

// multiple selection page.selectOption(‘select#colors’, [‘red’, ‘green’, ‘blue’]);

“‘

“‘python async # single selection matching the value await page.select_option(“select#colors”, “blue”) # single selection matching the label await page.select_option(“select#colors”, label=“blue”) # multiple selection await page.select_option(“select#colors”, value=[“red”, “green”, “blue”]) “`

“‘python sync # single selection matching the value page.select_option(“select#colors”, “blue”) # single selection matching both the label page.select_option(“select#colors”, label=“blue”) # multiple selection page.select_option(“select#colors”, value=[“red”, “green”, “blue”]) “`

Shortcut for main frame’s [‘method: Frame.selectOption`]

Raises:

  • (NotImplementedError)


1290
1291
1292
# File 'lib/playwright_api/page.rb', line 1290

def select_option(selector, values, noWaitAfter: nil, timeout: nil)
  raise NotImplementedError.new('select_option is not implemented yet.')
end

#set_content(html, timeout: nil, waitUntil: nil) ⇒ Object Also known as: content=



1294
1295
1296
# File 'lib/playwright_api/page.rb', line 1294

def set_content(html, timeout: nil, waitUntil: nil)
  wrap_impl(@impl.set_content(html, timeout: timeout, waitUntil: waitUntil))
end

#set_default_navigation_timeout(timeout) ⇒ Object Also known as: 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`

> NOTE: [‘method: Page.setDefaultNavigationTimeout`] takes priority over [`method: Page.setDefaultTimeout`],

‘method: BrowserContext.setDefaultTimeout`

and [‘method: BrowserContext.setDefaultNavigationTimeout`].

Raises:

  • (NotImplementedError)


1309
1310
1311
# File 'lib/playwright_api/page.rb', line 1309

def set_default_navigation_timeout(timeout)
  raise NotImplementedError.new('set_default_navigation_timeout is not implemented yet.')
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`].

Raises:

  • (NotImplementedError)


1317
1318
1319
# File 'lib/playwright_api/page.rb', line 1317

def set_default_timeout(timeout)
  raise NotImplementedError.new('set_default_timeout is not implemented yet.')
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.

Raises:

  • (NotImplementedError)


1325
1326
1327
# File 'lib/playwright_api/page.rb', line 1325

def set_extra_http_headers(headers)
  raise NotImplementedError.new('set_extra_http_headers is not implemented yet.')
end

#set_input_files(selector, files, noWaitAfter: nil, timeout: nil) ⇒ Object

This method expects selector to point to an [input element](developer.mozilla.org/en-US/docs/Web/HTML/Element/input).

Sets the value of the file input to these file paths or files. If some of the filePaths are relative paths, then they are resolved relative to the the current working directory. For empty array, clears the selected files.

Raises:

  • (NotImplementedError)


1335
1336
1337
# File 'lib/playwright_api/page.rb', line 1335

def set_input_files(selector, files, noWaitAfter: nil, timeout: nil)
  raise NotImplementedError.new('set_input_files is not implemented yet.')
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.

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.

“‘js const page = await browser.newPage(); await page.setViewportSize(

width: 640,
height: 480,

); await page.goto(‘example.com’); “‘

“‘python async page = await browser.new_page() await page.set_viewport_size(640, “height”: 480) await page.goto(“example.com”) “`

“‘python sync page = browser.new_page() page.set_viewport_size(640, “height”: 480) page.goto(“example.com”) “`



1366
1367
1368
# File 'lib/playwright_api/page.rb', line 1366

def set_viewport_size(viewportSize)
  wrap_impl(@impl.set_viewport_size(viewportSize))
end

#tap_point(selector, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) ⇒ Object

This method taps an element matching selector by performing the following steps:

  1. Find an element match matching selector. If there is none, wait until a matching element is attached to the DOM.

  2. 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.

  3. Scroll the element into view if needed.

  4. Use [‘property: Page.touchscreen`] to tap the center of the element, or the specified position.

  5. 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 rejects with a TimeoutError. Passing zero timeout disables this.

> NOTE: [‘method: Page.tap`] requires that the hasTouch option of the browser context be set to true.

Shortcut for main frame’s [‘method: Frame.tap`].

Raises:

  • (NotImplementedError)


1385
1386
1387
1388
1389
1390
1391
1392
1393
# File 'lib/playwright_api/page.rb', line 1385

def tap_point(
      selector,
      force: nil,
      modifiers: nil,
      noWaitAfter: nil,
      position: nil,
      timeout: nil)
  raise NotImplementedError.new('tap_point is not implemented yet.')
end

#text_content(selector, timeout: nil) ⇒ Object

Returns element.textContent.

Raises:

  • (NotImplementedError)


1396
1397
1398
# File 'lib/playwright_api/page.rb', line 1396

def text_content(selector, timeout: nil)
  raise NotImplementedError.new('text_content is not implemented yet.')
end

#titleObject

Returns the page’s title. Shortcut for main frame’s [‘method: Frame.title`].



1401
1402
1403
# File 'lib/playwright_api/page.rb', line 1401

def title
  wrap_impl(@impl.title)
end

#touchscreenObject

property



113
114
115
# File 'lib/playwright_api/page.rb', line 113

def touchscreen # property
  wrap_impl(@impl.touchscreen)
end

#type_text(selector, text, delay: nil, noWaitAfter: nil, timeout: nil) ⇒ Object

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`].

“‘js await page.type(’#mytextarea’, ‘Hello’); // Types instantly await page.type(‘#mytextarea’, ‘World’, 100); // Types slower, like a user “‘

“‘python async await page.type(“#mytextarea”, “hello”) # types instantly await page.type(“#mytextarea”, “world”, delay=100) # types slower, like a user “`

“‘python sync page.type(“#mytextarea”, “hello”) # types instantly page.type(“#mytextarea”, “world”, delay=100) # types slower, like a user “`

Shortcut for main frame’s [‘method: Frame.type`].



1427
1428
1429
1430
1431
1432
1433
1434
# File 'lib/playwright_api/page.rb', line 1427

def type_text(
      selector,
      text,
      delay: nil,
      noWaitAfter: nil,
      timeout: nil)
  wrap_impl(@impl.type_text(selector, text, delay: delay, noWaitAfter: noWaitAfter, timeout: timeout))
end

#uncheck(selector, force: nil, noWaitAfter: nil, timeout: nil) ⇒ Object

This method unchecks an element matching selector by performing the following steps:

  1. Find an element match matching selector. If there is none, wait until a matching element is attached to the DOM.

  2. Ensure that matched element is a checkbox or a radio input. If not, this method rejects. If the element is already unchecked, this method returns immediately.

  3. 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.

  4. Scroll the element into view if needed.

  5. Use [‘property: Page.mouse`] to click in the center of the element.

  6. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

  7. Ensure that the element is now unchecked. If not, this method rejects.

When all steps combined have not finished during the specified timeout, this method rejects with a TimeoutError. Passing zero timeout disables this.

Shortcut for main frame’s [‘method: Frame.uncheck`].

Raises:

  • (NotImplementedError)


1451
1452
1453
# File 'lib/playwright_api/page.rb', line 1451

def uncheck(selector, force: nil, noWaitAfter: nil, timeout: nil)
  raise NotImplementedError.new('uncheck is not implemented yet.')
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.

Raises:

  • (NotImplementedError)


1456
1457
1458
# File 'lib/playwright_api/page.rb', line 1456

def unroute(url, handler: nil)
  raise NotImplementedError.new('unroute is not implemented yet.')
end

#urlObject

Shortcut for main frame’s [‘method: Frame.url`].



1461
1462
1463
# File 'lib/playwright_api/page.rb', line 1461

def url
  wrap_impl(@impl.url)
end

#videoObject

Video object associated with this page.

Raises:

  • (NotImplementedError)


1466
1467
1468
# File 'lib/playwright_api/page.rb', line 1466

def video
  raise NotImplementedError.new('video is not implemented yet.')
end

#viewport_sizeObject



1470
1471
1472
# File 'lib/playwright_api/page.rb', line 1470

def viewport_size
  wrap_impl(@impl.viewport_size)
end

#visible?(selector, timeout: nil) ⇒ Boolean

Returns whether the element is [visible](./actionability.md#visible).

Returns:

  • (Boolean)

Raises:

  • (NotImplementedError)


1015
1016
1017
# File 'lib/playwright_api/page.rb', line 1015

def visible?(selector, timeout: nil)
  raise NotImplementedError.new('visible? is not implemented yet.')
end

#wait_for_event(event, optionsOrPredicate: nil, &block) ⇒ Object



1840
1841
1842
# File 'lib/playwright_api/page.rb', line 1840

def wait_for_event(event, optionsOrPredicate: nil, &block)
  wrap_impl(@impl.wait_for_event(event, optionsOrPredicate: optionsOrPredicate, &wrap_block_call(block)))
end

#wait_for_function(pageFunction, arg: nil, polling: nil, timeout: nil) ⇒ Object

Returns when the pageFunction returns a truthy value. It resolves to a JSHandle of the truthy value.

The waitForFunction can be used to observe viewport size change:

“‘js const { webkit } = require(’playwright’); // Or ‘chromium’ or ‘firefox’.

(async () =>

const browser = await webkit.launch();
const page = await browser.newPage();
const watchDog = page.waitForFunction(() => window.innerWidth < 100);
await page.setViewportSize({width: 50, height: 50);
await watchDog;
await browser.close();

})(); “‘

“‘python async import asyncio from playwright.async_api import async_playwright

async def run(playwright):

webkit = playwright.webkit
browser = await webkit.launch()
page = await browser.new_page()
await page.evaluate("window.x = 0; setTimeout(() => { window.x = 100 }, 1000);", force_expr=True)
await page.wait_for_function("() => window.x > 0")
await browser.close()

async def main():

async with async_playwright() as playwright:
    await run(playwright)

asyncio.run(main()) “‘

“‘python sync from playwright.sync_api import sync_playwright

def run(playwright):

webkit = playwright.webkit
browser = webkit.launch()
page = browser.new_page()
page.evaluate("window.x = 0; setTimeout(() => { window.x = 100 }, 1000);", force_expr=True)
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:

“‘js const selector = ’.foo’; await page.waitForFunction(selector => !!document.querySelector(selector), selector); “‘

“‘python async selector = “.foo” await page.wait_for_function(“selector => !!document.querySelector(selector)”, selector) “`

“‘python sync selector = “.foo” page.wait_for_function(“selector => !!document.querySelector(selector)”, selector) “`

Shortcut for main frame’s [‘method: Frame.waitForFunction`].

Raises:

  • (NotImplementedError)


1570
1571
1572
# File 'lib/playwright_api/page.rb', line 1570

def wait_for_function(pageFunction, arg: nil, polling: nil, timeout: nil)
  raise NotImplementedError.new('wait_for_function is not implemented yet.')
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.

“‘js await page.click(’button’); // Click triggers navigation. await page.waitForLoadState(); // The promise resolves after ‘load’ event. “‘

“‘python async await page.click(“button”) # click triggers navigation. await page.wait_for_load_state() # the promise resolves after “load” event. “`

“‘python sync page.click(“button”) # click triggers navigation. page.wait_for_load_state() # the promise resolves after “load” event. “`

“‘js const [popup] = await Promise.all([

page.waitForEvent('popup'),
page.click('button'), // Click triggers a popup.

]) await popup.waitForLoadState(‘domcontentloaded’); // The promise resolves after ‘domcontentloaded’ event. console.log(await popup.title()); // Popup is ready to use. “‘

“‘python async async with page.expect_popup() as page_info:

await page.click("button") # click triggers a popup.

popup = await page_info.value

# Following resolves after "domcontentloaded" event.

await popup.wait_for_load_state(“domcontentloaded”) print(await popup.title()) # popup is ready to use. “‘

“‘python sync with page.expect_popup() as page_info:

page.click("button") # click triggers a popup.

popup = page_info.value

# Following resolves after "domcontentloaded" event.

popup.wait_for_load_state(“domcontentloaded”) print(popup.title()) # popup is ready to use. “‘

Shortcut for main frame’s [‘method: Frame.waitForLoadState`].

Raises:

  • (NotImplementedError)


1624
1625
1626
# File 'lib/playwright_api/page.rb', line 1624

def wait_for_load_state(state: nil, timeout: nil)
  raise NotImplementedError.new('wait_for_load_state is not implemented yet.')
end

#wait_for_navigation(timeout: nil, url: nil, waitUntil: nil, &block) ⇒ Object



1830
1831
1832
# File 'lib/playwright_api/page.rb', line 1830

def wait_for_navigation(timeout: nil, url: nil, waitUntil: nil, &block)
  wrap_impl(@impl.wait_for_navigation(timeout: timeout, url: url, waitUntil: waitUntil, &wrap_block_call(block)))
end

#wait_for_request(urlOrPredicate, timeout: nil) ⇒ Object



1835
1836
1837
# File 'lib/playwright_api/page.rb', line 1835

def wait_for_request(urlOrPredicate, timeout: nil)
  wrap_impl(@impl.wait_for_request(urlOrPredicate, timeout: timeout))
end

#wait_for_response(urlOrPredicate, timeout: nil) ⇒ Object



1845
1846
1847
# File 'lib/playwright_api/page.rb', line 1845

def wait_for_response(urlOrPredicate, timeout: nil)
  wrap_impl(@impl.wait_for_response(urlOrPredicate, timeout: timeout))
end

#wait_for_selector(selector, state: nil, timeout: nil) ⇒ Object

Returns when element specified by selector satisfies state option. Returns null if waiting for hidden or detached.

Wait for the selector to satisfy state option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method selector already satisfies the condition, the method will return immediately. If the selector doesn’t satisfy the condition for the timeout milliseconds, the function will throw.

This method works across navigations:

“‘js const { chromium } = require(’playwright’); // Or ‘firefox’ or ‘webkit’.

(async () => {

const browser = await chromium.launch();
const page = await browser.newPage();
for (let currentURL of ['https://google.com', 'https://bbc.com']) {
  await page.goto(currentURL);
  const element = await page.waitForSelector('img');
  console.log('Loaded image: ' + await element.getAttribute('src'));
}
await browser.close();

})(); “‘

“‘python async import asyncio from playwright.async_api import async_playwright

async def run(playwright):

chromium = playwright.chromium
browser = await chromium.launch()
page = await browser.new_page()
for current_url in ["https://google.com", "https://bbc.com"]:
    await page.goto(current_url, wait_until="domcontentloaded")
    element = await page.wait_for_selector("img")
    print("Loaded image: " + str(await element.get_attribute("src")))
await browser.close()

async def main():

async with async_playwright() as playwright:
    await run(playwright)

asyncio.run(main()) “‘

“‘python sync from playwright.sync_api import sync_playwright

def run(playwright):

chromium = playwright.chromium
browser = chromium.launch()
page = browser.new_page()
for current_url in ["https://google.com", "https://bbc.com"]:
    page.goto(current_url, wait_until="domcontentloaded")
    element = page.wait_for_selector("img")
    print("Loaded image: " + str(element.get_attribute("src")))
browser.close()

with sync_playwright() as playwright:

run(playwright)

“‘

Raises:

  • (NotImplementedError)


1786
1787
1788
# File 'lib/playwright_api/page.rb', line 1786

def wait_for_selector(selector, state: nil, timeout: nil)
  raise NotImplementedError.new('wait_for_selector is not implemented yet.')
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.

“‘js // wait for 1 second await page.waitForTimeout(1000); “`

“‘python async # wait for 1 second await page.wait_for_timeout(1000) “`

“‘python sync # wait for 1 second page.wait_for_timeout(1000) “`

Shortcut for main frame’s [‘method: Frame.waitForTimeout`].

Raises:

  • (NotImplementedError)


1812
1813
1814
# File 'lib/playwright_api/page.rb', line 1812

def wait_for_timeout(timeout)
  raise NotImplementedError.new('wait_for_timeout is not implemented yet.')
end

#workersObject

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

Raises:

  • (NotImplementedError)


1820
1821
1822
# File 'lib/playwright_api/page.rb', line 1820

def workers
  raise NotImplementedError.new('workers is not implemented yet.')
end