☰ See All Chapters |
Puppeteer Page
In puppeteer each web page is considered as Page object. Page provides methods to interact with any of the current web page component. A puppeteer Browser instance can have multiple Page objects. (One browser can open multiple web pages.)
This example creates a page, navigates it to a URL, and then saves a screenshot:
const puppeteer = require('puppeteer'); async function example() { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://tools4testing.com/'); await page.screenshot({ path: 'example.png' }); await browser.close(); } example(); |
In any automation framework, to perform any user actions or to automate any element/component, first we have to get the elements/components instances. Page object provides below methods to get the elements. All these methods take String expression representing the locators/selectors. We learn about locators/selectors in next chapter. If it is confusing for you and facing difficulty in understanding, we suggest skip this chapter for now and first you read Selectors chapter and come back here.
Method | Description |
page.$(selectorExpression) | Returns a Promise with ElementHandle. ElementHandle is an instance of located element. If selectorExpression matches multiple elemenets then first matching element will be returned. |
page.$$(selectorExpression) | Returns a Promise with array of ElementHandle. In this case if selectorExpression matches with multiple elements, then all those elements will be returned in an array. |
page.$x(xPathExpression) | Returns a Promise with array of ElementHandle. In this case if xpathExpression matches with multiple elements, then all those elements will be returned in an array. If xpathExpression matches only one element the array will have only one element. |
Page object also provides methods to apply functions on located elements.
Method | Description |
page.$eval(selectorExpression, pageFunction[, ...args]) | This method will apply the pageFunction on the first matching element and returns Promise with return value of pageFunction. |
page.$$eval(selectorExpression, pageFunction[, ...args]) | This method will apply the pageFunction on the all matching element and returns Promise with return value of pageFunction. |
All Chapters