mirror of
https://github.com/puppeteer/puppeteer
synced 2024-06-14 14:02:48 +00:00
252 lines
16 KiB
Markdown
252 lines
16 KiB
Markdown
|
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
|
|||
|
|
|||
|
[Home](./index.md) > [puppeteer](./puppeteer.md) > [Page](./puppeteer.page.md)
|
|||
|
|
|||
|
## Page class
|
|||
|
|
|||
|
Page provides methods to interact with a single tab or [extension background page](https://developer.chrome.com/extensions/background_pages) in Chromium.
|
|||
|
|
|||
|
<b>Signature:</b>
|
|||
|
|
|||
|
```typescript
|
|||
|
export declare class Page extends EventEmitter
|
|||
|
```
|
|||
|
<b>Extends:</b> [EventEmitter](./puppeteer.eventemitter.md)
|
|||
|
|
|||
|
## Remarks
|
|||
|
|
|||
|
One Browser instance might have multiple Page instances.
|
|||
|
|
|||
|
The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the `Page` class.
|
|||
|
|
|||
|
## Example 1
|
|||
|
|
|||
|
This example creates a page, navigates it to a URL, and then \* saves a screenshot:
|
|||
|
|
|||
|
```js
|
|||
|
const puppeteer = require('puppeteer');
|
|||
|
|
|||
|
(async () => {
|
|||
|
const browser = await puppeteer.launch();
|
|||
|
const page = await browser.newPage();
|
|||
|
await page.goto('https://example.com');
|
|||
|
await page.screenshot({path: 'screenshot.png'});
|
|||
|
await browser.close();
|
|||
|
})();
|
|||
|
|
|||
|
```
|
|||
|
The Page class extends from Puppeteer's [EventEmitter](./puppeteer.eventemitter.md) class and will emit various events which are documented in the [PageEmittedEvents](./puppeteer.pageemittedevents.md) enum.
|
|||
|
|
|||
|
## Example 2
|
|||
|
|
|||
|
This example logs a message for a single page `load` event:
|
|||
|
|
|||
|
```js
|
|||
|
page.once('load', () => console.log('Page loaded!'));
|
|||
|
|
|||
|
```
|
|||
|
To unsubscribe from events use the `off` method:
|
|||
|
|
|||
|
```js
|
|||
|
function logRequest(interceptedRequest) {
|
|||
|
console.log('A request was made:', interceptedRequest.url());
|
|||
|
}
|
|||
|
page.on('request', logRequest);
|
|||
|
// Sometime later...
|
|||
|
page.off('request', logRequest);
|
|||
|
|
|||
|
```
|
|||
|
|
|||
|
## Properties
|
|||
|
|
|||
|
| Property | Modifiers | Type | Description |
|
|||
|
| --- | --- | --- | --- |
|
|||
|
| [accessibility](./puppeteer.page.accessibility.md) | | [Accessibility](./puppeteer.accessibility.md) | |
|
|||
|
| [coverage](./puppeteer.page.coverage.md) | | [Coverage](./puppeteer.coverage.md) | |
|
|||
|
| [keyboard](./puppeteer.page.keyboard.md) | | [Keyboard](./puppeteer.keyboard.md) | |
|
|||
|
| [mouse](./puppeteer.page.mouse.md) | | [Mouse](./puppeteer.mouse.md) | |
|
|||
|
| [touchscreen](./puppeteer.page.touchscreen.md) | | [Touchscreen](./puppeteer.touchscreen.md) | |
|
|||
|
| [tracing](./puppeteer.page.tracing.md) | | [Tracing](./puppeteer.tracing.md) | |
|
|||
|
|
|||
|
## Methods
|
|||
|
|
|||
|
| Method | Modifiers | Description |
|
|||
|
| --- | --- | --- |
|
|||
|
| [$(selector)](./puppeteer.page._.md) | | Runs <code>document.querySelector</code> within the page. If no element matches the selector, the return value resolves to <code>null</code>. |
|
|||
|
| [$$(selector)](./puppeteer.page.__.md) | | The method runs <code>document.querySelectorAll</code> within the page. If no elements match the selector, the return value resolves to <code>[]</code>. |
|
|||
|
| [$$eval(selector, pageFunction, args)](./puppeteer.page.__eval.md) | | This method runs <code>Array.from(document.querySelectorAll(selector))</code> within the page and passes the result as the first argument to the <code>pageFunction</code>. |
|
|||
|
| [$eval(selector, pageFunction, args)](./puppeteer.page._eval.md) | | This method runs <code>document.querySelector</code> within the page and passes the result as the first argument to the <code>pageFunction</code>. |
|
|||
|
| [$x(expression)](./puppeteer.page._x.md) | | The method evaluates the XPath expression relative to the page document as its context node. If there are no such elements, the method resolves to an empty array. |
|
|||
|
| [addScriptTag(options)](./puppeteer.page.addscripttag.md) | | Adds a <code><script></code> tag into the page with the desired URL or content. |
|
|||
|
| [addStyleTag(options)](./puppeteer.page.addstyletag.md) | | Adds a <code><link rel="stylesheet"></code> tag into the page with the desired URL or a <code><style type="text/css"></code> tag with the content. |
|
|||
|
| [authenticate(credentials)](./puppeteer.page.authenticate.md) | | Provide credentials for <code>HTTP authentication</code>. |
|
|||
|
| [bringToFront()](./puppeteer.page.bringtofront.md) | | Brings page to front (activates tab). |
|
|||
|
| [browser()](./puppeteer.page.browser.md) | | Get the browser the page belongs to. |
|
|||
|
| [browserContext()](./puppeteer.page.browsercontext.md) | | Get the browser context that the page belongs to. |
|
|||
|
| [click(selector, options)](./puppeteer.page.click.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.mouse](./puppeteer.page.mouse.md) to click in the center of the element. If there's no element matching <code>selector</code>, the method throws an error. |
|
|||
|
| [close(options)](./puppeteer.page.close.md) | | |
|
|||
|
| [content()](./puppeteer.page.content.md) | | |
|
|||
|
| [cookies(urls)](./puppeteer.page.cookies.md) | | 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. |
|
|||
|
| [deleteCookie(cookies)](./puppeteer.page.deletecookie.md) | | |
|
|||
|
| [emulate(options)](./puppeteer.page.emulate.md) | | Emulates given device metrics and user agent. This method is a shortcut for calling two methods: [Page.setUserAgent()](./puppeteer.page.setuseragent.md) and [Page.setViewport()](./puppeteer.page.setviewport.md) To aid emulation, Puppeteer provides a list of device descriptors that can be obtained via the [Puppeteer.devices](./puppeteer.puppeteer.devices.md) <code>page.emulate</code> will resize the page. A lot of websites don't expect phones to change size, so you should emulate before navigating to the page. |
|
|||
|
| [emulateIdleState(overrides)](./puppeteer.page.emulateidlestate.md) | | Emulates the idle state. If no arguments set, clears idle state emulation. |
|
|||
|
| [emulateMediaFeatures(features)](./puppeteer.page.emulatemediafeatures.md) | | |
|
|||
|
| [emulateMediaType(type)](./puppeteer.page.emulatemediatype.md) | | |
|
|||
|
| [emulateNetworkConditions(networkConditions)](./puppeteer.page.emulatenetworkconditions.md) | | |
|
|||
|
| [emulateTimezone(timezoneId)](./puppeteer.page.emulatetimezone.md) | | |
|
|||
|
| [emulateVisionDeficiency(type)](./puppeteer.page.emulatevisiondeficiency.md) | | Simulates the given vision deficiency on the page. |
|
|||
|
| [evaluate(pageFunction, args)](./puppeteer.page.evaluate.md) | | |
|
|||
|
| [evaluateHandle(pageFunction, args)](./puppeteer.page.evaluatehandle.md) | | |
|
|||
|
| [evaluateOnNewDocument(pageFunction, args)](./puppeteer.page.evaluateonnewdocument.md) | | Adds a function which would be invoked in one of the following scenarios:- whenever the page is navigated- whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame.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 <code>Math.random</code>. |
|
|||
|
| [exposeFunction(name, puppeteerFunction)](./puppeteer.page.exposefunction.md) | | The method adds a function called <code>name</code> on the page's <code>window</code> object. When called, the function executes <code>puppeteerFunction</code> in node.js and returns a <code>Promise</code> which resolves to the return value of <code>puppeteerFunction</code>.If the puppeteerFunction returns a <code>Promise</code>, it will be awaited.NOTE: Functions installed via <code>page.exposeFunction</code> survive navigations. |
|
|||
|
| [focus(selector)](./puppeteer.page.focus.md) | | This method fetches an element with <code>selector</code> and focuses it. If there's no element matching <code>selector</code>, the method throws an error. |
|
|||
|
| [frames()](./puppeteer.page.frames.md) | | |
|
|||
|
| [goBack(options)](./puppeteer.page.goback.md) | | This method navigate to the previous page in history. |
|
|||
|
| [goForward(options)](./puppeteer.page.goforward.md) | | This method navigate to the next page in history. |
|
|||
|
| [goto(url, options)](./puppeteer.page.goto.md) | | |
|
|||
|
| [hover(selector)](./puppeteer.page.hover.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.mouse](./puppeteer.page.mouse.md) to hover over the center of the element. If there's no element matching <code>selector</code>, the method throws an error. |
|
|||
|
| [isClosed()](./puppeteer.page.isclosed.md) | | Indicates that the page has been closed. |
|
|||
|
| [isJavaScriptEnabled()](./puppeteer.page.isjavascriptenabled.md) | | |
|
|||
|
| [mainFrame()](./puppeteer.page.mainframe.md) | | |
|
|||
|
| [metrics()](./puppeteer.page.metrics.md) | | |
|
|||
|
| [on(eventName, handler)](./puppeteer.page.on.md) | | Listen to page events. |
|
|||
|
| [once(eventName, handler)](./puppeteer.page.once.md) | | |
|
|||
|
| [pdf(options)](./puppeteer.page.pdf.md) | | |
|
|||
|
| [queryObjects(prototypeHandle)](./puppeteer.page.queryobjects.md) | | This method iterates the JavaScript heap and finds all objects with the given prototype. |
|
|||
|
| [reload(options)](./puppeteer.page.reload.md) | | |
|
|||
|
| [screenshot(options)](./puppeteer.page.screenshot.md) | | |
|
|||
|
| [select(selector, values)](./puppeteer.page.select.md) | | Triggers a <code>change</code> and <code>input</code> event once all the provided options have been selected. If there's no <code><select></code> element matching <code>selector</code>, the method throws an error. |
|
|||
|
| [setBypassCSP(enabled)](./puppeteer.page.setbypasscsp.md) | | Toggles bypassing page's Content-Security-Policy. |
|
|||
|
| [setCacheEnabled(enabled)](./puppeteer.page.setcacheenabled.md) | | Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled. |
|
|||
|
| [setContent(html, options)](./puppeteer.page.setcontent.md) | | |
|
|||
|
| [setCookie(cookies)](./puppeteer.page.setcookie.md) | | |
|
|||
|
| [setDefaultNavigationTimeout(timeout)](./puppeteer.page.setdefaultnavigationtimeout.md) | | This setting will change the default maximum navigation time for the following methods and related shortcuts:- [page.goBack(options)](./puppeteer.page.goback.md)- [page.goForward(options)](./puppeteer.page.goforward.md)- [page.goto(url,options)](./puppeteer.page.goto.md)- [page.reload(options)](./puppeteer.page.reload.md)- [page.setContent(html,options)](./puppeteer.page.setcontent.md)- [page.waitForNavigation(options)](./puppeteer.page.waitfornavigation.md) |
|
|||
|
| [setDefaultTimeout(timeout)](./puppeteer.page.setdefaulttimeout.md) | | |
|
|||
|
| [setExtraHTTPHeaders(headers)](./puppeteer.page.setextrahttpheaders.md) | | The extra HTTP headers will be sent with every request the page initiates. NOTE: All HTTP header names are lowercased. (HTTP headers are case-insensitive, so this shouldn’t impact your server code.) NOTE: page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests. |
|
|||
|
| [setGeolocation(options)](./puppeteer.page.setgeolocation.md) | | Sets the page's geolocation. |
|
|||
|
| [setJavaScriptEnabled(enabled)](./puppeteer.page.setjavascriptenabled.md) | | |
|
|||
|
| [setOfflineMode(enabled)](./puppeteer.page.setofflinemode.md) | | |
|
|||
|
| [setRequestInterception(value)](./puppeteer.page.setrequestinterception.md) | | |
|
|||
|
| [setUserAgent(userAgent, userAgentMetadata)](./puppeteer.page.setuseragent.md) | | |
|
|||
|
| [setViewport(viewport)](./puppeteer.page.setviewport.md) | | <code>page.setViewport</code> 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.In the case of multiple pages in a single browser, each page can have its own viewport size. |
|
|||
|
| [tap(selector)](./puppeteer.page.tap.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.touchscreen](./puppeteer.page.touchscreen.md) to tap in the center of the element. If there's no element matching <code>selector</code>, the method throws an error. |
|
|||
|
| [target()](./puppeteer.page.target.md) | | |
|
|||
|
| [title()](./puppeteer.page.title.md) | | |
|
|||
|
| [type(selector, text, options)](./puppeteer.page.type.md) | | Sends a <code>keydown</code>, <code>keypress/input</code>, and <code>keyup</code> event for each character in the text.To press a special key, like <code>Control</code> or <code>ArrowDown</code>, use [Keyboard.press()](./puppeteer.keyboard.press.md). |
|
|||
|
| [url()](./puppeteer.page.url.md) | | |
|
|||
|
| [viewport()](./puppeteer.page.viewport.md) | | |
|
|||
|
| [waitFor(selectorOrFunctionOrTimeout, options, args)](./puppeteer.page.waitfor.md) | | |
|
|||
|
| [waitForFileChooser(options)](./puppeteer.page.waitforfilechooser.md) | | This method is typically coupled with an action that triggers file choosing. The following example clicks a button that issues a file chooser and then responds with <code>/tmp/myfile.pdf</code> as if a user has selected this file.
|
|||
|
```js
|
|||
|
const [fileChooser] = await Promise.all([
|
|||
|
page.waitForFileChooser(),
|
|||
|
page.click('#upload-file-button'),
|
|||
|
// some button that triggers file selection
|
|||
|
]);
|
|||
|
await fileChooser.accept(['/tmp/myfile.pdf']);
|
|||
|
|
|||
|
```
|
|||
|
NOTE: This must be called before the file chooser is launched. It will not return a currently active file chooser. |
|
|||
|
| [waitForFunction(pageFunction, options, args)](./puppeteer.page.waitforfunction.md) | | The <code>waitForFunction</code> can be used to observe viewport size change:
|
|||
|
```
|
|||
|
const puppeteer = require('puppeteer');
|
|||
|
(async () => {
|
|||
|
const browser = await puppeteer.launch();
|
|||
|
const page = await browser.newPage();
|
|||
|
const watchDog = page.waitForFunction('window.innerWidth < 100');
|
|||
|
await page.setViewport({ width: 50, height: 50 });
|
|||
|
await watchDog;
|
|||
|
await browser.close();
|
|||
|
})();
|
|||
|
|
|||
|
```
|
|||
|
To pass arguments from node.js to the predicate of <code>page.waitForFunction</code> function:
|
|||
|
```
|
|||
|
const selector = '.foo';
|
|||
|
await page.waitForFunction(
|
|||
|
(selector) => !!document.querySelector(selector),
|
|||
|
{},
|
|||
|
selector
|
|||
|
);
|
|||
|
|
|||
|
```
|
|||
|
The predicate of <code>page.waitForFunction</code> can be asynchronous too:
|
|||
|
```
|
|||
|
const username = 'github-username';
|
|||
|
await page.waitForFunction(
|
|||
|
async (username) => {
|
|||
|
const githubResponse = await fetch(
|
|||
|
`https://api.github.com/users/${username}`
|
|||
|
);
|
|||
|
const githubUser = await githubResponse.json();
|
|||
|
// show the avatar
|
|||
|
const img = document.createElement('img');
|
|||
|
img.src = githubUser.avatar_url;
|
|||
|
// wait 3 seconds
|
|||
|
await new Promise((resolve, reject) => setTimeout(resolve, 3000));
|
|||
|
img.remove();
|
|||
|
},
|
|||
|
{},
|
|||
|
username
|
|||
|
);
|
|||
|
|
|||
|
```
|
|||
|
|
|
|||
|
| [waitForNavigation(options)](./puppeteer.page.waitfornavigation.md) | | This resolves when the page navigates to a new URL or reloads. It is useful when you run code that will indirectly cause the page to navigate. Consider this example:
|
|||
|
```js
|
|||
|
const [response] = await Promise.all([
|
|||
|
page.waitForNavigation(), // The promise resolves after navigation has finished
|
|||
|
page.click('a.my-link'), // Clicking the link will indirectly cause a navigation
|
|||
|
]);
|
|||
|
|
|||
|
```
|
|||
|
|
|
|||
|
| [waitForRequest(urlOrPredicate, options)](./puppeteer.page.waitforrequest.md) | | |
|
|||
|
| [waitForResponse(urlOrPredicate, options)](./puppeteer.page.waitforresponse.md) | | |
|
|||
|
| [waitForSelector(selector, options)](./puppeteer.page.waitforselector.md) | | Wait for the <code>selector</code> to appear in page. If at the moment of calling the method the <code>selector</code> already exists, the method will return immediately. If the <code>selector</code> doesn't appear after the <code>timeout</code> milliseconds of waiting, the function will throw.This method works across navigations:
|
|||
|
```js
|
|||
|
const puppeteer = require('puppeteer');
|
|||
|
(async () => {
|
|||
|
const browser = await puppeteer.launch();
|
|||
|
const page = await browser.newPage();
|
|||
|
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 browser.close();
|
|||
|
})();
|
|||
|
|
|||
|
```
|
|||
|
|
|
|||
|
| [waitForTimeout(milliseconds)](./puppeteer.page.waitfortimeout.md) | | Causes your script to wait for the given number of milliseconds. |
|
|||
|
| [waitForXPath(xpath, options)](./puppeteer.page.waitforxpath.md) | | Wait for the <code>xpath</code> to appear in page. If at the moment of calling the method the <code>xpath</code> already exists, the method will return immediately. If the <code>xpath</code> doesn't appear after the <code>timeout</code> milliseconds of waiting, the function will throw.This method works across navigation
|
|||
|
```js
|
|||
|
const puppeteer = require('puppeteer');
|
|||
|
(async () => {
|
|||
|
const browser = await puppeteer.launch();
|
|||
|
const page = await browser.newPage();
|
|||
|
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 browser.close();
|
|||
|
})();
|
|||
|
|
|||
|
```
|
|||
|
|
|
|||
|
| [workers()](./puppeteer.page.workers.md) | | |
|