The Accessibility class provides methods for inspecting Chromium's accessibility tree. The accessibility tree is used by assistive technology such as screen readers or switches.
Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that might have wildly different output.
Blink - Chrome's rendering engine - has a concept of "accessibility tree", which is than translated into different platform-specific APIs. Accessibility namespace gives users access to the Blink Accessibility Tree.
Most of the accessibility tree gets filtered out when converting from Blink AX Tree to Platform-specific AX-Tree or by assistive technologies themselves. By default, Puppeteer tries to approximate this filtering, exposing only the "interesting" nodes of the tree.
see Accessibility for more details
helpers to troubleshoot automation issues.
see Diagnostics for more information
automate keyboard presses.
see Keyboard for more information
contains helpers for operating beyond the current page. such as get/set values between page navigations, and logging details that will be stored in your response output.
See the Meta documentation for more details.
contains functions for controlling the mouse on the page. Clicking, moving, etc. Also see Touchscreen and Keyboard.
See the Mouse documentation for more details.
automate taps on a touch screen.
See Touchscreen for more information
perform performance traces.
selector
<string> A selector to query page forpageFunction
<function(Array<Element<)< Function to be evaluated in browser contextargs
<...Serializable|JSHandle< Arguments to pass to pageFunctionThis method runs Array.from(document.querySelectorAll(selector)) within the page and passes it as the first argument to pageFunction.
If pageFunction returns a Promise, then page.$$eval would wait for the promise to resolve and return its value.
Examples:
const divsCounts = await page.$$eval('div', divs => divs.length);
selector
<string> A selector to query page forpageFunction
<function(Element)> Function to be evaluated in browser contextargs
<...Serializable|JSHandle> Arguments to pass to pageFunctionThis method runs document.querySelector within the page and passes it as the first argument to pageFunction. If there's no element matching selector, the method throws an error.
If pageFunction returns a Promise, then page.$eval would wait for the promise to resolve and return its value.
Examples:
const searchValue = await page.$eval('#search', el => el.value);
const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
const html = await page.$eval('.main-container', e => e.outerHTML);
options
<Object>url
<string> URL of a script to be added.content
<string> Raw JavaScript content to be injected into frame.type
<string> Script type. Use 'module' in order to load a Javascript ES6 module. See script for more details.Adds a <script> tag into the page with the desired url or content.
options
<Object>url
<string> URL of the <link< tag.content
<string> Raw CSS content to be injected into frame.Adds a <link rel="stylesheet" > tag into the page with the desired url or a <style type="text/css"> tag with the content.
credentialOptions
<?Object<username
<string>password
<string>Provide credentials for HTTP authentication.
To disable authentication, pass null.
Brings page to front (activates tab).
selector
<string> A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked.options
<Object>button
<"left"|"right"|"middle"< Defaults to left.clickCount
<number> defaults to 1. See UIEvent.detail.delay
<number> Time to wait between mousedown and mouseup in milliseconds. Defaults to 0.This method fetches an element with selector, scrolls it into view if needed, and then uses page.mouse to click in the center of the element. If there's no element matching selector, the method throws an error.
Bear in mind that if click() triggers a navigation event and there's a separate page.waitForNavigation() promise to be resolved, you may end up with a race condition that yields unexpected results. The correct pattern for click and wait for navigation is the following:
const [response] = await Promise.all([
page.waitForNavigation(waitOptions),
page.click(selector, clickOptions),
]);
Very similar to Render.content but instead of storing the html/text to output, it is returned by this function.
a string containing html/plainText.
urls
<...string>name
<string>value
<string>domain
<string>path
<string>expires
<number> Unix time in seconds.size
<number>httpOnly
<boolean>secure
<boolean>session
<boolean>sameSite
<"Strict"|"Lax"|"Extended"|"None">If no URLs are specified, this method returns cookies for the current page URL. If URLs are specified, only cookies for those URLs are returned.
cookies
<...Object>name
<string> requiredurl
<string>domain
<string>path
<string>call this to signal that your request is done and the results can be returned to you. Especially useful in conjunction with Page.manualWait but can also be used to finish execution earlier than normal (not wait for ajax scripts, etc).
options
<Object>viewport
<Object>width
<number> page width in pixels.height
<number> page height in pixels.deviceScaleFactor
<number> Specify device scale factor (can be thought of as dpr). Defaults to 1.isMobile
<boolean> Whether the meta viewport tag is taken into account. Defaults to false.hasTouch
<boolean> Specifies if viewport supports touch events. Defaults to falseisLandscape
<boolean> Specifies if viewport is in landscape mode. Defaults to false.userAgent
<string>Emulates given device metrics and user agent. This method is a shortcut for calling two methods:
page.setUserAgent(userAgent)
page.setViewport(viewport)
NOTE: page.emulate
will resize the page. A lot of websites don't expect phones to change size, so you should emulate before navigating to the page.
Given an array of media feature objects, emulates CSS media features on the page. Passing null resets all.
mediaType
<?string> Changes the CSS media type of the page. The only allowed values are 'screen
', 'print
' and null
. Passing null
disables media emulation.Changes the timezone of the page. See ICU’s metaZones.txt for a list of supported timezone IDs. Passing null disables timezone emulation.
pageFunction
<function|string> Function to be evaluated in the page contextargs
<...Serializable|JSHandle> Arguments to pass to pageFunctionIf the function passed to the page.evaluate returns a Promise, then page.evaluate would wait for the promise to resolve and return its value.
If the function passed to the page.evaluate returns a non-Serializable value, then 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.
Here is an example request JSON that returns true if the body tag exists.
{
url: "https://example.com",
renderType: "automation",
overseerScript:'await page.waitForNavigation(); var exists = await page.evaluate(()=>{ return document.getElementsByTagName("body").length >0 }); if(exists!=null){page.meta.store.set("key",exists);} ',
}
Passing arguments to pageFunction:
//overseerScript code
const result = await page.evaluate(x => {
return Promise.resolve(8 * x);
}, 7);
console.log(result); // prints "56"
A string can also be passed in instead of a function:
//overseerScript code
console.log(await page.evaluate('1 + 2')); // prints "3"
const x = 10;
console.log(await page.evaluate(`1 + ${x}`)); // prints "11"
ElementHandle instances can be passed as arguments to the page.evaluate:
//overseerScript code
const bodyHandle = await page.$eval('body');
const html = await page.evaluate(body => body.innerHTML, bodyHandle);
await bodyHandle.dispose();
pageFunction
<function|string> Function to be evaluated in browser contextargs
<...Serializable> Arguments to pass to pageFunctionAdds a function which would be invoked in one of the following scenarios:
The function is invoked 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 the navigator.languages property before the page loads:
overseerScript:'await page.evaluateOnNewDocument(() => {Object.defineProperty(navigator, "language", {get: function() {return ["de-DE","de"];}});Object.defineProperty(navigator, "languages", {get: function() {return ["de-DE", "de"];}});});',
selector
<string> A selector of an element to focus. If there are multiple elements satisfying the selector, the first will be focused.This method fetches an element with selector and focuses it. If there's no element matching selector, the method throws an error.
options
<Object> Navigation parameters which might have the following properties:timeout
<number> Maximum navigation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the page.setDefaultNavigationTimeout(timeout)
or page.setDefaultTimeout(timeout)
methods.waitUntil
<string|Array<string>> When to consider navigation succeeded, defaults to load. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either:load
- consider navigation to be finished when the load event is fired.domcontentloaded
- consider navigation to be finished when the DOMContentLoaded event is fired.networkidle0
- consider navigation to be finished when there are no more than 0 network connections for at least 500 ms.networkidle2
- consider navigation to be finished when there are no more than 2 network connections for at least 500 ms.Navigate to the previous page in history.
options
<Object> Navigation parameters which might have the following properties:timeout
<number> Maximum navigation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the page.setDefaultNavigationTimeout(timeout)
or page.setDefaultTimeout(timeout)
methods.waitUntil
<string|Array<<string>> When to consider navigation succeeded, defaults to load. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either:load
- consider navigation to be finished when the load event is fired.domcontentloaded
- consider navigation to be finished when the DOMContentLoaded event is fired.networkidle0
- consider navigation to be finished when there are no more than 0 network connections for at least 500 ms.networkidle2
- consider navigation to be finished when there are no more than 2 network connections for at least 500 ms.Navigate to the next page in history.
url
<string> URL to navigate page to. The url should include scheme, e.g. https://.options
<Object> Navigation parameters which might have the following properties:timeout
<number> Maximum navigation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the page.setDefaultNavigationTimeout(timeout)
or page.setDefaultTimeout(timeout)
methods.waitUntil
<string|Array<string>> When to consider navigation succeeded, defaults to load. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either:load
- consider navigation to be finished when the load
event is fired.domcontentloaded
- consider navigation to be finished when the DOMContentLoaded
event is fired.networkidle0
- consider navigation to be finished when there are no more than 0 network connections for at least 500
ms.networkidle2
- consider navigation to be finished when there are no more than 2 network connections for at least 500
ms.referer
<string> Referer header value. If provided it will take preference over the referer header value set by page.setExtraHTTPHeaders()
.page.goto
will throw an error if:
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 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.
selector
<string> A selector to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered.options
allows choosing a specific frame (main frame, or a child IFrame). defaults to searching all frames, stopping at the first successful execution.This method fetches an element with selector, scrolls it into view if needed, and then uses page.mouse to hover over the center of the element. If there's no element matching selector, the method throws an error.
Page is guaranteed to have a main frame which persists during navigations.
call this to signal the API to NOT complete when it thinks the page is done loading. Instead, it will complete only when you call Page.done
returns: <Promise<Object>> Object containing metrics as key/value pairs.
NOTE All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.
The page.on()
allows you to attach to events of the page.
For example:
page.on('load', () => page.meta.log('Page loaded!'));
For details of all events you can hook, please see PageOnEvents
shortcut to [[render.pdf]]
reloads the page. can pass navigation options.
shortcut to [[render.screenshot]]
manipulate a html select element.
selector
<string> A selector to query page forvalues
<...string> Values of options to select. If the <select< has the multiple attribute, all values are considered, otherwise only the first one is taken into account.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.
page.select('select#colors', 'blue'); // single selection
page.select('select#colors', 'red', 'green', 'blue'); // multiple selections
html
<string> HTML markup to assign to the page.options
<Object> Parameters which might have the following properties:timeout
<number> Maximum time in milliseconds for resources to load, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the page.setDefaultNavigationTimeout(timeout) or page.setDefaultTimeout(timeout) methods.waitUntil
{string|Array{string>> When to consider setting markup succeeded, defaults to load. Given an array of event strings, setting content is considered to be successful after all events have been fired. Events can be either:load
- consider setting content to be finished when the load event is fired.domcontentloaded
- consider setting content to be finished when the DOMContentLoaded event is fired.networkidle0
- consider setting content to be finished when there are no more than 0 network connections for at least 500 ms.networkidle2
- consider setting content to be finished when there are no more than 2 network connections for at least 500 ms.cookies
<...Object>name
<string> requiredvalue
<string> requiredurl
<string>domain
<string>path
<string>expires
<number> Unix time in seconds.httpOnly
<boolean>secure
<boolean>sameSite
<"Strict"|"Lax">await page.setCookie(cookieObject1, cookieObject2);
This setting will change the default maximum navigation time for the following methods and related shortcuts:
NOTE page.setDefaultNavigationTimeout
takes priority over page.setDefaultTimeout
default: 15000 (15 seconds)
This setting will change the default maximum time for the following methods and related shortcuts:
**NOTE** ```page.setDefaultNavigationTimeout``` takes priority over ```page.setDefaultTimeout```
The extra HTTP headers will be sent with every request the page initiates.
NOTE page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.
Sets the page's geolocation.
await page.setGeolocation({latitude: 59.95, longitude: 30.31667});
enabled
<boolean> When true, enables offline mode for the page.viewport
<Object>width
<number> page width in pixels. requiredheight
<number> page height in pixels. requireddeviceScaleFactor
<number> Specify device scale factor (can be thought of as dpr). Defaults to 1.isMobile
<boolean> Whether the meta viewport tag is taken into account. Defaults to false.hasTouch
<boolean> Specifies if viewport supports touch events. Defaults to falseisLandscape
<boolean> Specifies if viewport is in landscape mode. Defaults to false.NOTE in certain cases, setting viewport will reload the page in order to set the isMobile or hasTouch properties.
In the case of multiple pages in a single browser, each page can have its own viewport size.
page.setViewport
will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport before navigating to the page.
await page.setViewport({
width: 640,
height: 480,
deviceScaleFactor: 1,
});
await page.goto('https://example.com');
selector
<string> A selector to search for element to tap. If there are multiple elements satisfying the selector, the first will be tapped.This method fetches an element with selector, scrolls it into view if needed, and then uses page.touchscreen to tap in the center of the element. If there's no element matching selector, the method throws an error.
selector
<string> A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used.text
<string> A text to type into a focused element.options
<Object>delay
<number> Time to wait between key presses in milliseconds. Defaults to 0.Sends a keydown, keypress/input, and keyup event for each character in the text.
To press a special key, like Control or ArrowDown, use keyboard.press.
page.type('#mytextarea', 'Hello'); // Types instantly
page.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
returns a promise resolving to the url.
reads the page's current viewport.
returns: <?Object<
width
<number> page width in pixels.height
<number> page height in pixels.deviceScaleFactor
<number> Specify device scale factor (can be though of as dpr). Defaults to 1.isMobile
<boolean> Whether the meta viewport tag is taken into account. Defaults to false.hasTouch
<boolean> Specifies if viewport supports touch events. Defaults to falseisLandscape
<boolean> Specifies if viewport is in landscape mode. Defaults to false.waits for the given number of ms
returns if/when the current page domContentLoaded event is triggered
pageFunction
<function|string> Function to be evaluated in browser contextoptions
<Object> Optional waiting parameterspolling
<string|number< An interval at which the pageFunction is executed, defaults to raf. If polling is a number, then it is treated as an interval in milliseconds at which the function would be executed. If polling is a string, then it can be one of the following values:raf
- to constantly execute pageFunction in requestAnimationFrame callback. This is the tightest polling mode which is suitable to observe styling changes.mutation
- to execute pageFunction on every DOM mutation.timeout
<number> maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the page.setDefaultTimeout(timeout) method.args
<...Serializable|JSHandle> Arguments to pass to pageFunctionThe waitForFunction can be used to observe viewport size change:
const watchDog = page.waitForFunction('window.innerWidth < 100');
await page.setViewport({width: 50, height: 50});
await watchDog;
await page.done();
});
To pass arguments from node.js to the predicate of page.waitForFunction function:
const selector = '.foo';
await page.waitForFunction(selector => !!document.querySelector(selector), {}, selector);
returns if/when the current page load event is triggered
IMPORTANT This function will not complete until a page Navigation occurs. Thus if the page is already loaded, this function will stall until the next page load occurs.
So if you await
a command that performs a navigation (eg: await page.click("input[type=button][value=Login]");
)
then if the next line calls await page.waitForNavigation()
it will block until the api call times out. A workaround is to make sure you do not await
the command that calls the navigation (the page.click()
command).
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. Consider this example:
selector
<string> A selector of an element to wait foroptions
<Object> Optional waiting parametersvisible
<boolean> wait for element to be present in DOM and to be visible, i.e. to not have display: none or visibility: hidden CSS properties. Defaults to false.hidden
<boolean> wait for element to not be found in the DOM or to be hidden, i.e. have display: none or visibility: hidden CSS properties. Defaults to false.timeout
<number> maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the page.setDefaultTimeout(timeout) method.Wait for the selector to appear in page. If at the moment of calling the method the selector already exists, the method will return immediately. If the selector doesn't appear after the timeout milliseconds of waiting, the function will throw.
This method works across navigations:
let currentURL;
page
.waitForSelector('img')
.then(() => console.log('First URL with image: ' + currentURL));
for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com'])
await page.goto(currentURL);
await page.done();
xpath
<string> A xpath of an element to wait foroptions
<Object> Optional waiting parametersvisible
<boolean> wait for element to be present in DOM and to be visible, i.e. to not have display: none or visibility: hidden CSS properties. Defaults to false.hidden
<boolean> wait for element to not be found in the DOM or to be hidden, i.e. have display: none or visibility: hidden CSS properties. Defaults to false.timeout
<number> maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the page.setDefaultTimeout(timeout) method.Wait for the xpath to appear in page. If at the moment of calling the method the xpath already exists, the method will return immediately. If the xpath doesn't appear after the timeout milliseconds of waiting, the function will throw.
This method works across navigations:
let currentURL;
page
.waitForXPath('//img')
.then(() => console.log('First URL with image: ' + currentURL));
for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com'])
await page.goto(currentURL);
await page.done();
This method returns all of the dedicated WebWorkers associated with the page.
Methods to interact with a single page (tab) in the Chrome browser.
This is usable globally from your script (no need to construct a new instance)
Example showing basic automaton:
// every time the domLoaded event triggers page.on("domcontentloaded",()=>{ //scrolls the element into view then clicks it with the left mouse button page.click("#btn2"); });