Puppeteer Tutorial
Puppeteer Tutorial
i
Puppeteer
Audience
This tutorial is designed for professionals working in software testing who want to hone
their skills on a robust automation testing tool like Puppeteer. It can be used to test
applications developed in Angular and Angularjs.
Prerequisites
Prior going through this tutorial, you should have a fair knowledge on JavaScript and
object oriented programming concepts. Besides, a good understanding of basics in
testing is important to proceed with the tutorial.
All the content and graphics published in this e-book are the property of Tutorials Point
(I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or
republish any contents or a part of contents of this e-book in any manner without written
consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely
as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I)
Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of
our website or its contents including this tutorial. If you discover any errors on our
website or in this tutorial, please notify us at [email protected]
i
Puppeteer
Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
1. Puppeteer – Introduction.......................................................................................................................... 1
ii
Puppeteer
Handling Checkboxes..................................................................................................................................... 92
iv
1. Puppeteer – Introduction Puppeteer
Puppeteer is used for automation and streamlining of the frontend development and
testing respectively. It was introduced by Google. Puppeteer is based on the Node.js
library and is open-source.
Puppeteer contains APIs to interact and manage Chrome browser in headless mode or
Chromium (following the protocols in DevTools). However, it can also be used for non-
headless execution on browsers like Chrome/Chromium/Edge/Firefox.
Puppeteer can be used for the automating majority of UI testing, keyboards, mouse
movements, and so on. It can be used to test applications developed in Angular and
Angularjs. The actions like web page crawling and scraping can be performed with
Puppeteer.
If we follow the npm trends for Puppeteer download for the last few years, we shall
observe an upward trend towards the use of Puppeteer (available from the below link):
https://www.npmtrends.com/puppeteer
1
Puppeteer
Puppeteer Architecture
Puppeteer utilises the Node library that gives a top-class API for managing Chromium or
Chrome browsers. This is done by following the protocols of DevTools.
2
2. Puppeteer — Element Handling Puppeteer
For this, our first job is to identify the element. To get the property of an element
uniquely we need to inspect it (right-click on the element then select the option Inspect).
The ElementHandle objects are created by the methods - page.$, page.$$ and page.$x.
These objects refer to an element or tag in a page.
page.$(locator value)
This method yields a Promise with the ElementHandle. The ElementHandle is an object of
the identified element. If there are multiple elements having the same locator value,
then only the first matching element from the top left corner of the page shall be
returned.
page.$$(locator value)
This method yields a Promise with an array of ElementHandle. If there are multiple
elements having the same locator value, then all matching elements shall be returned in
the form of an array.
page.$x(xpath value)
This method yields a Promise with an array of ElementHandle. If there are multiple
elements having the same xpath value, then all matching elements shall be returned in
the form of an array. In case, there is one matching element, then the array returned
shall have a single element.
In the below image, let us take the example of an element having the li tag (having a
parent element ul) and class attribute value as heading. To identify it using the
ElementHandle method on the page, the expression should be as follows:
3
Puppeteer
Now, refer the image given below of an element having the li tag
Types of Locators
The types of locators in Puppeteer are listed below:
ID
Class
Type
Xpath
Attribute
Type
To work with the above locators we should have the basic understanding of HTML code.
Let us take an example of an edit box having the below mentioned properties:
Here, input is the tagname. A tag in HTML may or may not have attributes. The type,
class, name, id and so on are the attributes of the element.
For example, in the expression class = "gsc-input", text to the left of = is the attribute
name (class) and to the right of = is the attribute value (gsc-input).
An attribute may or may not have a value assigned. Also, if a value is assigned, then it
should be enclosed in double or single quotes. The value of an attribute is set by a
developer as per his choice.
4
3. Puppeteer — Usage of Google Puppeteer
Puppeteer can be used for scrapping contents from a webpage. The scrapping
means pulling out data from a particular website.
Puppeteer can be used to capture screenshots. It can be used to export web
pages in the form of a PDF.
Puppeteer does not require an external driver or library. It can be run on the
actual browser in a headless mode.
It can be used as a good alternative to other browser automation tools like
Selenium or Cypress. Sometimes, puppeteer features are even better than both
of them.
It is super-fast in execution and can be used to execute tests in headless and
headed modes.
Puppeteer has a very agile community support having more than 60,000 starts in
GitHub. Refer the link given herewith: https://github.com/puppeteer/puppeteer
Puppeteer supports headless execution and hence it can be used in platforms like
Unix, Linux, Cloud, AWS, and so on.
It can be used to crawl a SPA (Single Page Application) and produce pre-rendered
content. The crawling means saving a local static object of a webpage and
utilising it offline in the absence of the real webpage obtained from the internet.
It can be used for the automating majority of UI testing, keyboards, mouse
movements, form submissions etc.
Puppeteer can be used to construct a recent, automated test environment. It can
run tests on the latest version Chrome by utilising the most recent features of
JavaScript and browser.
Puppeteer can be used to obtain the timeline trace of a web application to
determine its performance. Moreover, it can be used to check the Chrome
Extensions and to obtain the coverage of HTML and CSS utilized by a webpage.
5
4. Puppeteer — Installation of NodeJS Puppeteer
Puppeteer code implementation is done using JavaScript. For this, NodeJS has to be
installed since it is a JavaScript engine. Only after its installation, we can execute
Puppeteer tests.
https://nodejs.org/en/download/
Step 2: As per the local operating system (Windows, Mac or Linux) we are using, click
on the link to download the Installer.
Step 3: Once the installer is downloaded, click on it. We shall be navigated to the
Node.js Installer welcome screen. Click on Continue.
6
Puppeteer
7
Puppeteer
Step 6: Once the success message of Nodejs installation is displayed, click on Close.
8
Puppeteer
Step 7: To check if Nodejs is installed successfully, open the terminal and run the
command: node.
The version of the Nodejs installed in the machine should get displayed.
9
5. Puppeteer — VS Code Configuration Puppeteer
The steps to install the Visual Studio (VS) Code are listed below:
https://code.visualstudio.com/
Step 2: Depending on the local operating system we have for example - macOS, Linux
or Windows, we need to choose the link for download.
Step 3: A zip file gets downloaded after clicking the Download button. After downloading
this file has completed, click on it and the Visual Studio Code application should become
available for use.
Step 4: Double-click it and the Visual Studio Code application should launch along with
the welcome page.
10
Puppeteer
11
6. Puppeteer — Installation Puppeteer
The details on how to install NodeJs is discussed in detail in the Chapter of Installation of
NodeJS.
Step 3: Launch the Visual Studio Code application and click on the Open folder link and
import the folder we have created in Step2.
The details on how to install VS Code is discussed in detail in the Chapter of VS Code
Configuration.
Step 4: Open the terminal and move from the current directory to the directory of the
empty folder that we have created in Step 2. Then run the following command:
npm
12
Puppeteer
Or,
npm i puppeteer
Step 6: For installation of Puppeteer core, run the below mentioned command:
npm i puppeteer-core
Step 7: After the installation of Puppeteer and Puppeteer core, we shall find the
node_modules folder and package.json file generated within the empty folder we created
in Step 2.
13
Puppeteer
Step 8: While working on a test, we have to add the below Puppeteer library in the
code.
const pt = require('puppeteer')
14
7. Puppeteer — Basic Test on Puppeteer Puppeteer
To start with a basic test on Puppeteer, we have to follow the below mentioned steps:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
15
Puppeteer
node <filename>
node testcase1.js
After the command has been successfully executed, a new file called the
tutorialspoint.png gets created within the page directory. It contains the captured
screenshot of the page launched in the browser in a headless mode.
16
8. Puppeteer — Non Headless Execution Puppeteer
By default, Puppeteer executes the test in headless Chromium. This means if we are
running a test using Puppeteer, then we won't be able to view the execution in the
browser.
To enable execution in the headed mode, we have to add the parameter: headless:false
in the code.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer, which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
17
Puppeteer
Step 3: Add the below code within the testcase1.js file created.
node <filename>
node testcase1.js
18
Puppeteer
After the command has been successfully executed, we shall see the execution getting
triggered in a headed mode.
19
9. Puppeteer — Comparison between Puppeteer
The major differences between Puppeteer and Selenium are given below:
7. Puppeteer can be used for API testing API testing with Selenium is difficult.
by utilising the requests and the
responses.
8. Puppeteer can be used to verify the Selenium cannot be used to verify the
count of CSS and JavaScript files count of CSS and JavaScript files
utilised for loading a webpage. utilised for loading a webpage.
20
Puppeteer
11. Puppeteer can be used to obtain the Selenium cannot be used to obtain the
time needed for a page to load. time needed for a page to load.
13. Puppeteer was first introduced in the Selenium was first introduced in the
year 2017. year 2004.
21
10. Puppeteer — Comparison between Puppeteer
The major differences between Puppeteer and Protractor are given below:
4. Puppeteer can be used for API testing API testing with Protractor is difficult.
by utilising the requests and the
responses.
22
Puppeteer
Let us observe the npm trends of Puppeteer and Protractor for the last two years. We
shall observe an upward trend towards the use of Puppeteer than Protractor (available
from the below link):
https://www.npmtrends.com/protractor-vs-puppeteer
23
11. Puppeteer — Comparison between Puppeteer
4. VS Code and Webstorm are mostly Cypress has its individual IDE.
used as an IDE for Puppeteer.
8. Puppeteer APIs are not easier to use Cypress APIs are easier to use than
than Cypress. Puppeteer.
9. Puppeteer comes free of cost. Cypress has both free and paid
versions.
24
Puppeteer
11. Grouping of tests for execution Grouping of tests for execution can be
cannot be done in Puppeteer. done in Cypress.
Let us observe the npm trends of Puppeteer and Cypress for the last two years. We shall
observe an upward trend towards the use of both Puppeteer and Cypress (available from
the below link):
https://www.npmtrends.com/cypress-vs-puppeteer
25
12. Puppeteer — Browser Operations Puppeteer
The browser operations can be done by Puppeteer with the help of below given methods:
launch()
It is used to open new browsers and connect with an instance of Chromium. It has some
optional parameters which are as follows:
Product: This is of String type and is used to point to the browser to be launched. The
syntax is as follows:
headless: This is of Boolean type(default value is true) and it has to be set with false
value inorder to execute the tests in headed mode. The syntax is as follows:
devtools: This is of Boolean type. If it is set to true, then DevTools shall open
automatically in each browser tab. Also, the headless parameter should be set to false, if
devtools is set to true. The syntax is as follows:
slowMo: This is of type number. This parameter is used to slow down the Puppeteer
execution for some time, provided in milliseconds. The syntax is as follows:
goTo()
It is used to navigate to a webpage. The URL of the page to be navigated is passed as a
parameter. The syntax is as follows:
await page.goto('https://www.tutorialspoint.com/index.htm')
close()
It is used to close an opened browser. The syntax is as follows:
await browser.close()
26
Puppeteer
browserContexts()
This yields an array of all opened browser contexts.
createIncognitoBrowserContext()
It opens a new browser in incognito context.
defaultBrowserContext()
It yields a default browser context.
disconnect()
It is used to disconnect Puppeteer from the browser instance.
isConnected()
It is used to verify whether a browser is connected.
newPage()
It yields a Promise with a new page object.
pages()
It yields a Promise with an array of all open page objects.
process()
It yields a browser process if the instance is created with the launch method.
Furthermore, it yields a null value if the instance is created with the connect method.
target()
It yields the target for a browser.
targets()
It yields a Promise containing the array of all targets which are active.
27
13. Puppeteer — Handling Tabs Puppeteer
newPage()
We can open a new tab using this method available in the browser object. The syntax is
as follows:
close()
We can close the tab opened using this method. The syntax is as follows:
await p.close()
close()
We can close all the tabs opened using this method available in the browser object. The
syntax is as follows:
await browser.close()
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
node <filename>
node testcase1.js
29
Puppeteer
After the command has been successfully executed, a new file called the
tutorialspoint.png gets created within the page directory. It contains the captured
screenshot of the page launched in the browser.
30
14. Puppeteer — Basic Commands Puppeteer
title()
This command is used to obtain the title of the present page. The syntax is as follows:
await page.title()
url()
This command is used to obtain the URL of the application currently launched in the
browser. The syntax is as follows:
await page.url()
content()
This command is used to obtain the page source code The syntax is as follows:
await page.content()
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
31
Puppeteer
Step 3: Add the below code within the testcase1.js file created.
node <filename>
node testcase1.js
32
Puppeteer
After the command has been successfully executed, the page title - The Best Technical
Questions and Answers gets printed in the console. Also, the URL -
https://www.tutorialspoint.com/questions/index.php gets printed in the console. The
execution has happened in the headless mode.
33
15. Puppeteer with Firefox Puppeteer
We can run the tests developed in Puppeteer in Firefox. It must be remembered that
while executing the test in Firefox, Puppeteer uses its internal Firefox browser and not
the Firefox browser installed in the local system.
Step 1: We have to first install Puppeteer for the Firefox browser by executing the below
command:
const f = require('puppeteer-firefox')
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
34
Puppeteer
Step 3: Add the below code within the testcase1.js file created.
35
Puppeteer
await browser.close()
})
node <filename>
node testcase1.js
After the command has been successfully executed, the browser in which the test is
executed - Firefox/65.0 gets printed in the console.
36
16. Puppeteer with Chrome Puppeteer
The tests written in Puppeteer are executed in the Chrome or Chromium browser in a
headless mode by default. Also, we have to add the below Puppeteer library in the code.
const pt = require('puppeteer')
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
37
Puppeteer
node <filename>
node testcase1.js
After the command has been successfully executed, the browser in which the test is
executed - HeadlessChrome/92.0.4512.0 gets printed in the console.
38
17. Puppeteer — Handling Confirm Alerts Puppeteer
However in Puppeteer, the user has to give direction whether to accept or dismiss an
alert before it appears on the page. For this, the on event listener has to be triggered
using Puppeteer.
In the below given image, on clicking Click for JS Confirm, a confirm alert is displayed.
Let us obtain the text on the alert.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
39
Puppeteer
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function confirmAlert(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage();
//on event listener trigger
page.on('dialog', async dialog => {
//get alert message
console.log(dialog.message());
//accept alert
await dialog.accept();
})
40
Puppeteer
//launch URL
await page.goto('https://the-internet.herokuapp.com/javascript_alerts')
//identify element with xpath then click
const b = (await page.$x("//button[text()='Click for JS Confirm']"))[0]
b.click()
}
confirmAlert()
node <filename>
node testcase1.js
After the command has been successfully executed, the confirm alert text - I am a JS
Confirm gets printed in the console.
41
18. Puppeteer — Handling Drop-downs Puppeteer
We can handle drop downs in the UI while automating a test using Puppeteer. The static
drop downs are identified in the html code with the tagname as select and its options
have the tagname as option.
select()
This method is used to select an option from the dropdown. The value of the option to be
selected is passed as a parameter to this method. The syntax is as follows:
We can also select multiple options from a multi-select dropdown. The syntax is as
follows:
To obtain select value from the dropdown, we have to use the getProperty method and
pass value as a parameter to this field.
type()
This method is used to select an option from the dropdown. The value of the option to be
selected is passed as a parameter to this method. The syntax is as follows:
42
Puppeteer
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function dropDownHandle(){
//launch browser in headless mode
43
Puppeteer
node <filename>
node testcase1.j
After the command has been executed successfully, the value of the option selected in
the dropdown - subject is printed in the console.
44
19. Puppeteer — Locators Puppeteer
For this, our first job is to identify the element. To get the property of an element
uniquely we need to inspect it (right-click on the element then select the option Inspect).
The ElementHandle objects are created by the methods - page.$, page.$$ and page.$x.
These objects refer to an element or tag in a page.
To determine an element uniquely, we can either take the help of any of the attributes
within the html tag or we can use a combination of attributes on the html tag. Mostly
the id attribute is used since it is unique to a page.
However, if the id attribute is not present, we can use other attributes like the class,
name, and so on. In case the attributes like id, name, and class are not present, we can
utilise a distinct attribute available to only that tag or a combination of attributes and
their values to identify an element. For this, we have to use the xpath expression.
page.$(locator value)
This method yields a Promise with the ElementHandle. The ElementHandle is an object of
the identified element. If there are multiple elements having the same locator value,
then only the first matching element from the top left corner of the page shall be
returned.
page.$$(locator value)
This method yields a Promise with an array of ElementHandle. If there are multiple
elements having the same locator value, then all matching elements shall be returned in
the form of an array.
page.$x(xpath value)
This method yields a Promise with an array of ElementHandle. If there are multiple
elements having the same xpath value, then all matching elements shall be returned in
the form of an array. In case, there is one matching element, then the array returned
shall have a single element.
In the below given image, let us take the example of an element having the li tag(having
a parent element ul) and class attribute value as heading.
45
Puppeteer
To identify it using the ElementHandle method on the page, the expression should be as
follows:
To identify it using the ElementHandle method on an element, the expression should be:
Now, refer the image given below of an element having the li tag
Types of Locators
The types of locators in Puppeteer are listed below:
ID
Class
Type
Xpath
Attribute
Type
To work with the above locators we should have the basic understanding of HTML code.
Let us take an example of an edit box having the below properties:
46
Puppeteer
Here, input is the tagname. A tag in HTML may or may not have attributes. The type,
class, name, id and so on are the attributes of the element.
For example, in the expression id = "gsc-i-id1", text to the left of = is the attribute name
(id) and to the right of = is the attribute value (gsc-i-id1).
An attribute may or may not have a value assigned. Also, if a value is assigned, then it
should be enclosed in double or single quotes. The value of an attribute is set by a
developer as per his choice.
47
Puppeteer
We can identify the first checkbox in the above image, with the expression:
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function checkBoxHandle(){
//launch browser in headed mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage()
//launch URL
await page.goto('https://the-internet.herokuapp.com/checkboxes')
//identify element with xpath then click
const n = await page.$("input[type='checkbox']")
n.click()
49
Puppeteer
node <filename>
node testcase1.js
After the command has been executed successfully, the boolean value true is printed in
the console. This is returned by getProperty("checked") which returns true as the
checkbox is selected.
50
20. Puppeteer — Xpath Functions Puppeteer
To determine an element uniquely, we can either take the help of any of the attributes
within the html tag or we can use a combination of attributes on the html tag. Mostly the
id attribute is used since it is unique to a page.
However, if the id attribute is not present, we can use other attributes like the class,
name, and so on. In case the attributes like id, name, and class are not present, we can
utilise a distinct attribute available to only that tag or a combination of attributes and
their values to identify an element. For this, we have to use the xpath expression.
If there are duplicate attributes or no attribute for an element, then the function text() is
used to identify an element. In order to use the text() function, it is mandatory that the
element should have a text visible on the page.
If the value of an element or the text is partially dynamic in nature or very lengthy, we
can use the contains() function. In order to use the contains() function, it is mandatory
that the element should either have an attribute value or a text.
//tagname[contains(@attribute,'value')]
//tagname[contains(text(),'visible text on element')]
If the text of an element begins with a particular text, we can use the starts-with()
function to it.
In all the above functions, tagname is optional. Instead of tagname, we can use the
symbol *.
In the below image, let us identify the element - Library with the help of its displayed
text and then click on it.
51
Puppeteer
Here, we are working with the xpath selector, so we have to use the method:
page.$x(xpath value). The detail on this method is discussed in the Chapter - Puppeteer
Locators.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
52
Puppeteer
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function selectorFunTextXpath(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage()
//launch URL
await page.goto('https://www.tutorialspoint.com/index.htm')
//identify element with xpath function - text() then click
const b = (await page.$x("//*[text()='Library']"))[0]
b.click()
//wait for sometime
await page.waitForTimeout(4000)
//obtain URL after click
console.log(await page.url())
}
selectorFunTextXpath()
node <filename>
node testcase1.js
53
Puppeteer
After the command has been successfully executed, the URL of the page navigated on
clicking the element Library - https://www.tutorialspoint.com/tutorialslibrary.htm gets
printed in the console.
54
21. Puppeteer — Xpath Attributes Puppeteer
To determine an element uniquely, we can either take the help of any of the attributes
within the html tag or we can use a combination of attributes on the html tag. Mostly
the id attribute is used since it is unique to a page.
However, if the id attribute is not present, we can use other attributes like the class,
name, and so on. In case the attributes like id, name, and class are not present, we can
utilise a distinct attribute available to only that tag or a combination of attributes and
their values to identify an element. For this, we have to use the xpath expression.
If an xpath expression with a single attribute identifies multiple elements, we can use
more than one attribute in the xpath expression to locate a single element.
The format for writing an xpath with only one attribute is as follows:
//tagname[@attribute='value']
For multiple attributes, we can apply AND and OR conditions. The format for writing an
xpath with AND condition:
//tagName[@attribute1='value1'] [@attribute2='value2']
Or,
//tagName[@attribute1='value1' or @attribute2='value2']
We can also identify an element by applying the NOT condition on an attribute. The
format for writing an xpath with NOT condition:
//tagname[not(@attribute='value')]
Let us identify the below highlighted logo on the page with the help of the alt attribute
and then click on it.
55
Puppeteer
//img[@alt='tutorialspoint'].
Here, we are working with the xpath selector, so we have to use the method:
page.$x(xpath value). The detail on this method is discussed in the Chapter of Puppeteer
Locators.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
56
Puppeteer
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function selectorAttributeXpath(){
//launch browser in headed mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage()
//launch URL
await page.goto('https://www.tutorialspoint.com/questions/index.php')
//identify element with relative xpath then click
const b = (await page.$x("//img[@alt='tutorialspoint']"))[0]
b.click()
//wait for sometime
await page.waitForTimeout(4000)
//obtain URL after click
console.log(await page.url())
}
selectorAttributeXpath()
node <filename>
node testcase1.js
57
Puppeteer
After the command has been successfully executed, the URL of the page navigated on
clicking the logo image - https://www.tutorialspoint.com/index.htm gets printed in the
console.
58
22. Puppeteer — Xpath Grouping Puppeteer
To determine an element uniquely, we can either take the help of any of the attributes
within the html tag or we can use a combination of attributes on the html tag. Mostly
the id attribute is used since it is unique to a page.
However, if the id attribute is not present, we can use other attributes like the class,
name, and so on. In case the attributes like id, name, class are not present, we can
utilise a distinct attribute available to only that tag or a combination of attributes and
their values to identify an element. For this, we have to use the xpath expression.
Obtaining one element from a collection of matching elements by utilising the index is
known as the group index. If an xpath expression identifies multiple elements, then we
can use the group index.
The format for writing a group index is first the xpath expression followed by the index
number enclosed in []. It represents an xpath array with index starting from 1. The
function last() is used to point to the last element in the xpath array.
(/table/tbody/tr/td[1]/input)[last()]
The function position() is used to obtain an element at a particular position in the xpath
array. The syntax is as follows:
(/table/tbody/tr/td[1]/input)[position()=1]
The above xpath expression shall obtain the first element from the group of all the
matching elements.
In the below image, let us identify the highlighted edit box and input some text in it.
59
Puppeteer
In the above example, there are two columns (represented by td tags) in the table
having the tr tag as their parent. The input box is present in the first column.
//table/tbody/tr/td[1]/input
Here, we are working with the xpath selector, so we have to use the method:
page.$x(xpath value). The details on this method are discussed in the Chapter of
Puppeteer Locators.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
60
Puppeteer
//Puppeteer library
const pt= require('puppeteer')
async function selectorGroupXpath(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage()
//launch URL
await page.goto('https://www.tutorialspoint.com/index.htm')
//identify element with group index xpath then enter text
const f = (await page.$x("//table/tbody/tr/td[1]/input"))[0]
f.type("Puppeteer")
//wait for sometime
await page.waitForTimeout(4000)
//capture screenshot
await page.screenshot({
path: 'tutorialspoint.png'
});
//browser close
await browser.close()
}
selectorGroupXpath()
node <filename>
node testcase1.js
61
Puppeteer
After the command has been successfully executed, a new file called the
tutorialspoint.png gets created within the page directory. It contains the captured
screenshot of the page launched in the browser with the text Puppeteer.
62
23. Puppeteer — Absolute Xpath Puppeteer
To determine an element uniquely, we can either take the help of any of the attributes
within the html tag or we can use a combination of attributes on the html tag. Mostly
the id attribute is used since it is unique to a page.
However, if the id attribute is not present, we can use other attributes like the class,
name, and so on. In case the attributes like id, name, class are not present, we can
utilise a distinct attribute available to only that tag or a combination of attributes and
their values to identify an element. For this, we have to use the xpath expression. Also,
if the element on a page is dynamic, then xpath selector can be a good choice as a
selector.
Xpath can be of two types - absolute and relative. The absolute xpath begins with /
symbol and starts from the root node upto the element that we want to identify. An
example is given below for the same.
/html/body/div[1]/div/div[1]/a
Let us identify the below highlighted logo on the page with the help of the absolute
xpath and then click on it.
63
Puppeteer
html/body/header/div[4]/div[1]/div[1]/a/img.
Here, we are working with the xpath selector, so we have to use the method:
page.$x(xpath value). The detail on this method is discussed in the Chapter of Puppeteer
Locators.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
64
Puppeteer
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function selectorAbsoluteXpath(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage()
//launch URL
65
Puppeteer
await page.goto('https://www.tutorialspoint.com/about/about_careers.htm')
//identify element with absolute xpath then click
const b = (await page.$x("/html/body/header/div[4]/div[1]/div[1]/a/img"))[0]
b.click()
//wait for sometime
await page.waitForTimeout(4000)
//obtain URL after click
console.log(await page.url())
}
selectorAbsoluteXpath()
node <filename>
node testcase1.js
After the command has been successfully executed, the URL of the page navigated on
clicking the logo image - https://www.tutorialspoint.com/index.htm gets printed in the
console.
66
24. Puppeteer — Relative Xpath Puppeteer
To determine an element uniquely, we can either take the help of any of the attributes
within the html tag or we can use a combination of attributes on the html tag. Mostly
the id attribute is used since it is unique to a page.
However, if the id attribute is not present, we can use other attributes like the class,
name, and so on. In case the attributes like id, name, and class are not present, we can
utilise a distinct attribute available to only that tag or a combination of attributes and
their values to identify an element.
For this, we have to use the xpath expression. Also, if the element on a page is dynamic,
then xpath selector can be a good choice as a selector.
Relative Xpath
Xpath can be of two types - absolute and relative. A relative xpath begins from the
element to be located and not from the root.
It begins with the // symbol which refers to any descendant. Its advantage is that even if
an element is deleted or added in the DOM, the relative xpath for a specific element
remains unaffected.
//tagname[@attribute='value'].
Let us identify the below highlighted logo on the page with the help of the alt attribute
and then click on it.
//img[@alt='tutorialspoint'].
67
Puppeteer
Here, we are working with the xpath selector, so we have to use the method:
page.$x(xpath value). The detail on this method is discussed in the Chapter - Puppeteer
Locators.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function selectorRelativeXpath(){
//launch browser in headless mode
68
Puppeteer
node <filename>
node testcase1.js
After the command has been successfully executed, the URL of the page navigated on
clicking the logo image - https://www.tutorialspoint.com/index.htm gets printed in the
console.
69
25. Puppeteer — Xpath Axes Puppeteer
To determine an element uniquely, we can either take the help of any of the attributes
within the html tag or we can use a combination of attributes on the html tag. Mostly
the id attribute is used since it is unique to a page.
However, if the id attribute is not present, we can use other attributes like the class,
name, and so on. In case the attributes like id, name, and class are not present, we can
utilise a distinct attribute available to only that tag or a combination of attributes and
their values to identify an element.
For this, we have to use the xpath expression. Also, if the element on a page is dynamic,
then xpath selector can be a good choice as a selector.
The xpath is bi-directional which means we can traverse from the parent to the child
element and also from the child to the parent element. The details of xpath axes shall be
available in the below link:
https://www.tutorialspoint.com/xpath/xpath_axes.htm
In the below image, let us identify the highlighted edit box and obtain the value of its
class attribute - gsc-input.
In the above example, there are two columns (represented by td tags) in the table
having the tr tag as their parent. The input box is present in the first column.
//table/tbody/tr/child::td.
Here, we are working with the xpath selector, so we have to use the method:
page.$x(xpath value). The details on this method are discussed in the Chapter of
Puppeteer Locators.
70
Puppeteer
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function selectorAxesXpath(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
71
Puppeteer
await page.goto('https://www.tutorialspoint.com/index.htm')
//identify element with xpath axes
const n = (await page.$x("//table/tbody/tr/child::td"))[0]
// get value of class attribute
let v = await page.$eval("input",
n => n.getAttribute("class"))
console.log(v)
}
selectorAxesXpath()
node <filename>
node testcase1.js
After the command has been successfully executed, the value of the class attribute for
the element - gsc-input gets printed in the console.
72
26. Puppeteer — Type Selector Puppeteer
For this, our first job is to identify the element. If a tag is used only one time in a page,
we can use it as a type selector. If there are multiple elements with the same tag, only
the first matching element on the page shall be identified.
In the below example, let us identify the highlighted element having tagname h4 and
obtain its text - You are browsing the best resource for Online Education.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which is as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
73
Puppeteer
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function selectorType(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage()
//launch URL
await page.goto('https://www.tutorialspoint.com/index.htm')
//identify element with type selector
const n = await page.$("h4")
//obtain text
const text = await (await n.getProperty('textContent')).jsonValue()
console.log("Text is: " + text)
}
selectorType()
node <filename>
node testcase1.js
74
Puppeteer
After the command has been successfully executed, the text on the element - You are
browsing the best resource for Online Education gets printed in the console.
75
27. Puppeteer — Name Selector and Class Name Puppeteer
Selector
Name Selector
Once we navigate to a webpage, we have to interact with the webelements available on
the page like clicking a link/button, entering text within an edit box, and so on to
complete our automation test case.
For this, our first job is to identify the element. If a value of the name attribute is used
only one time in a page, we can use it as a name selector. If there are multiple elements
with the same name, only the first matching element on the page shall be identified.
Let us identify the edit box highlighted in the below image and enter text:
The element highlighted in the above image has the name attribute value as search. The
name selector expression for the above element shall be [name="search"].
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
76
Puppeteer
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function selectorName(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage();
//launch URL
await page.goto('https://www.tutorialspoint.com/index.htm')
//identify edit box with name
const f = await page.$('[name="search"]')
//enter text
f.type("Puppeteer")
77
Puppeteer
//browser close
await browser.close()
}
selectorName()
node <filename>
node testcase1.js
For this, our first job is to identify the element. If a class name is used only one time in a
page, we can use it as a class name selector. If there are multiple elements with the
same class name, only the first matching element on the page shall be identified.
In the below example, let us identify the highlighted element having class name heading
and obtain its text - About Tutorialspoint.
78
Puppeteer
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function getText(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
79
Puppeteer
await page.goto('https://www.tutorialspoint.com/about/about_careers.htm')
//identify element with class name
const f = await page.$(".heading")
//obtain text
const text = await (await f.getProperty('textContent')).jsonValue()
console.log("Text is: " + text)
}
getText()
node <filename>
node testcase1.js
After the command has been successfully executed, the text of the element - About
Tutorialspoint gets printed in the console.
80
28. Puppeteer — Id Selector Puppeteer
For this, our first job is to identify the element. An id attribute is generally unique in a
page and can be used as an id selector. It is a very useful locator and speeds up the
execution of automation tests in comparison to all the selectors.
In the below example, let us identify the highlighted element having id txtSearchText
and enter text into it.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
81
Puppeteer
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function selectorId(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage();
//launch URL
await page.goto('https://www.tutorialspoint.com/tutor_connect/index.php')
//identify element with id
const f = await page.$("#txtSearchText")
//enter text
f.type("Puppeteer")
82
Puppeteer
//browser close
await browser.close()
}
selectorId()
node <filename>
node testcase1.js
83
29. Puppeteer — Attribute Selector Puppeteer
For this, our first job is to identify the element. If an attribute and its value is used only
one time in a tag, we can use it as an attribute selector. If there are multiple elements
with the same attribute value, only the first matching element on the page shall be
identified.
Here, ul is the tagname and val is the value set for the name attribute.
In the below image, let us obtain the text - About Tutorialspoint for the highlighted
element:
The attribute selector expression for the above element shall be li[class='heading'].
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
84
Puppeteer
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function selectorAttribute(){
//launch browser in headed mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage()
//launch URL
await page.goto('https://www.tutorialspoint.com/about/about_careers.htm')
//identify element with attribute selector
const n = await page.$("li[class='heading']")
//obtain text
const t = await (await n.getProperty('textContent')).jsonValue()
85
Puppeteer
selectorAttribute()
node <filename>
node testcase1.js
After the command has been successfully executed, the text of the element - About
Tutorialspoint gets printed in the console.
86
30. Puppeteer — Handling Links/Button Puppeteer
In the below image, we shall click on the below highlighted link - Subscribe to Premium
Plan having tagname as h1:
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
87
Puppeteer
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function clickElement(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage()
//launch URL
await page.goto('https://www.tutorialspoint.com/index.htm')
//identify element then click
await page.click('h1');
//get page title after click
console.log(await page.title())
}
clickElement()
node <filename>
node testcase1.js
88
Puppeteer
After the command has been successfully executed, the title - Tutorials Point Paid
Subscription Packages - Tutorialspoint obtained after clicking the link - Subscribe to
Premium Plan gets printed in the console.
89
31. Puppeteer — Handling Edit Boxes and Puppeteer
Checkboxes
type()
This method is used to input text into an edit box and text area without replacing the
already present content.
We can enter text in an edit box with some delay. This is done by adding the parameter
{delay:time interval}. The time interval is expressed in the milliseconds.
To delete a text entered in an edit box, we have to perform the click event three times
on the field(with the parameter clickCount) and then press backspace. It is similar to
selecting all values in an edit box and then pressing backspace.
To get value entered in an edit box, we have to use the getProperty method and pass
value as a parameter to this field.
In the below image, let us input the text Puppeteer and then clear it.
90
Puppeteer
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which is as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
91
Puppeteer
//Puppeteer library
const pt= require('puppeteer')
async function enterText(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage();
//launch URL
await page.goto('https://www.tutorialspoint.com/index.htm')
//identify edit box
const f = await page.$("#gsc-i-id1")
//enter text
f.type("Puppeteer")
//clear text entered
await f.click({clickCount: 3})
//wait for sometime
await page.waitForTimeout(4000)
await page.keyboard.press('Backspace')
//browser close
await browser.close()
}
enterText()
node <filename>
node testcase1.js
Handling Checkboxes
We can handle checkboxes in the UI while automating a test using Puppeteer. The
checkboxes are identified in the html code with the tagname as input and type as
checkbox.
92
Puppeteer
click()
It is used to check and uncheck a checkbox. This method is a part of the ElementHandle
class.
93
Puppeteer
To verify if a checkbox is checked, we have to use the getProperty method and pass
value as a parameter to this field. It returns a Boolean value(true if checked, false if
not).
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
94
Puppeteer
node <filename>
node testcase1.js
After the command has been executed successfully, the boolean value true is printed in
the console. This is returned by the getProperty("checked") which returns true as the
checkbox is selected.
95
32. Puppeteer — Handling Frames Puppeteer
The frames in an html code are represented by the frames/iframe tag. Puppeteer can
handle frames by switching from the main page to the frame. To work with elements
inside a frame, first we have to identify the frame with the help of locators. The method
contentFrame is used to access the elements inside the frame.
Let us see the html code of an element inside a frame and obtain the text - BOTTOM
inside it.
The tagname highlighted in the above image is frame and the value of its name attribute
is frame-bottom.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
96
Puppeteer
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function frameHandle(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage()
//launch URL
await page.goto('https://the-internet.herokuapp.com/nested_frames')
//identify frame
const f = await page.$("frame[name='frame-bottom']")
97
Puppeteer
//move to frame
const x = await f.contentFrame();
node <filename>
node testcase1.js
After the command has been successfully executed, the text within the frame - BOTTOM
gets printed in the console.
98
33. Puppeteer — Keyboard Simulation Puppeteer
Puppeteer can perform keyboard simulation actions like pressing a key in the keyboard,
pressing the up, down keys, and so on. All these are done using the keyboard method.
Keyboard Methods
Some of the keyboard methods are as follows:
keyboard.press()
This method is used to simulate a key press. The key to be pressed is passed as a
parameter to this method. The syntax is as follows:
keyboard.press('Enter')
keyboard.type()
This method is used to simulate entering text from the keyboard. The text to be entered
is passed as a parameter to this method. The syntax is as follows:
keyboard.type('Puppeteer')
keyboard.sendCharacter()
It is same as keyboard.type(). The syntax is as follows:
keyboard.sendCharacter('Puppeteer')
keyboard.up()
This method is used to simulate pressing the up arrow from the keyboard. The syntax is
as follows:
keyboard.up()
keyboard.down()
This method is used to simulate pressing the down arrow from the keyboard. The syntax
is as follows:
keyboard.down()
In the below image, let us input a text and then press Enter.
99
Puppeteer
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
100
Puppeteer
//Puppeteer library
const pt= require('puppeteer')
async function keyboradSimulation(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage()
//launch URL
await page.goto('https://www.tutorialspoint.com/index.htm')
//identify edit box with id
const f = await page.$("#gsc-i-id1")
//enter text
f.type("Puppeteer")
//wait for sometime
await page.waitForTimeout(4000)
//press Enter
await page.keyboard.press('Enter')
//wait for sometime
await page.waitForTimeout(4000)
//identify element
const t = await page.$(".gsc-result-info")
//obtain text
const text = await (await t.getProperty('textContent')).jsonValue()
console.log("Text is: " + text)
}
keyboradSimulation()
node <filename>
node testcase1.js
After the command has been successfully executed, the text obtained on pressing Enter
after entering Puppeteer - About 39 results (0.15 seconds) gets printed in the console.
101
34. Puppeteer — Getting Element Text Puppeteer
We can get element text in Puppeteer. This is done with the help of the textContent
property. This property of the element is passed as a parameter to the getProperty
method.
In the below image, let us obtain the text - About Tutorialspoint for the highlighted
element:
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
102
Puppeteer
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function getText(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage()
//launch URL
await page.goto('https://www.tutorialspoint.com/about/about_careers.htm')
//identify element
const f = await page.$("[class='heading']")
//obtain text
const text = await (await f.getProperty('textContent')).jsonValue()
103
Puppeteer
getText()
node <filename>
node testcase1.js
After the command has been successfully executed, the text of the element - About
Tutorialspoint gets printed in the console.
104
35. Puppeteer — Getting Element Attribute Puppeteer
We can get attribute values of an element using Puppeteer. The attributes are added
within the HTML tag. They are used to describe the properties of an element. An
attribute and its value are defined in a key-value pair.
Here, input is the tagname. A tag in HTML may or may not have attributes. The type,
class , name, id and so on are the attributes of this element. For example, in id = gsc-i-
id1, text to the left of = is the attribute name(i.e id) and to the right of = is the attribute
value(i.e gsc-i-id1).
An attribute may or may not have a value assigned. Also, if a value is assigned, then it
should be enclosed in double or single quotes. The value of an attribute is set by a
developer as per his choice.
getAttribute()
This method is used to get the value of the attribute which is passed as a parameter to
this method. The syntax is as follows:
element.<attribute name>
The syntax is as follows:
105
Puppeteer
element.getProperty()
This method is used to get the value of the attribute which is passed as a parameter to
this method. The syntax is as follows:
In the below image, let us identify the highlighted edit box and obtain the value of its
class attribute - gsc-input.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
106
Puppeteer
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function getElementAttribute(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage()
//launch URL
await page.goto('https://www.tutorialspoint.com/index.htm')
//identify element with id
const n = await page.$("#gsc-i-id1")
//get class attribute
let v = await page.$eval("input",
n => n.getAttribute("class"))
console.log(v)
}
getElementAttribute()
node <filename>
node testcase1.js
107
Puppeteer
After the command has been successfully executed, the value of the class attribute for
the element - gsc-input gets printed in the console.
108
36. Puppeteer — Device Emulation Puppeteer
We can run tests with mobile configurations in Puppeteer and check the responsive
property of a webpage. The list of devices that the Puppeteer supports can be obtained
from the Chrome DevTools. Right-click on a page opened in the Chrome browser, then
select Inspect.
109
Puppeteer
To emulate a device, we have to use the method emulate() and the device to be
emulated is passed as a parameter to this method. The syntax for this method is as
follows:
110
Puppeteer
Let us emulate the device iPhone X using the emulate function in Puppeteer.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const puppeteer = require('puppeteer')
//launch browser in headed mode
puppeteer.launch({headless:false}).then(async browser => {
//browser new page
111
Puppeteer
node <filename>
node testcase1.js
112
Puppeteer
After the command has been successfully executed, a new file called the
iPhoneDevice.png gets created within the page directory. It contains the captured
screenshot of the emulated webpage for the iPhone X device.
113
37. Puppeteer — Disable JavaScript Puppeteer
We can disable JavaScript using Puppeteer. For this, we have to block the
requests/response based on its type. Let us make an attempt to launch a page by
disabling JavaScript.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
114
Puppeteer
//Puppeteer library
const pt = require('puppeteer')
pt.launch().then(async browser => {
node <filename>
node testcase1.js
115
38. Puppeteer — Synchronization Puppeteer
Puppeteer Page class contains methods to achieve synchronization. These methods are
used to wait for an action/element on the page. It waits for criteria to be met (a true
value). For example, we often wait for a text to appear on the page.
Synchronization methods
The synchronization methods in Puppeteer are listed below:
waitFor
This method is used to wait for a specific amount of time before resolving a Promise. The
syntax is as follows:
await page.waitFor(4000)
waitForSelector
This method is used to wait for an element to be visible or disappear from the webpage.
The syntax is as follows:
page.waitForSelector(
selector,
{options : value}
)
The waitForSelector accepts two parameters. The first parameter is the selector value of
an element. The second parameter is the array of options. The options are listed below:
Visible: Puppeteer shall wait till an element locator is visible on the page. The
default value is false.
Hidden: Puppeteer shall wait till an element locator is hidden from the page. The
default value is false.
Timeout: The maximum wait time for an element in milliseconds. The default
value is 30000. If the timeout is set to zero, this is discarded.
The default wait time can be modified by using the method given below:
page.setDefaultTimeout(6000)
For example,
116
Puppeteer
waitForXpath
This method is used to wait for element/elements identified by xpath to be visible or
disappear from the webpage. The syntax is as follows:
page.waitXpath(
Xpath value,
{options : value}
)
The waitForXpath accepts two parameters. The first parameter is the xpath selector
value of an element. The second parameter is the array of options. The options are listed
below:
Visible: Puppeteer shall wait till an element locator is visible on the page. The
default value is false.
Hidden: Puppeteer shall wait till an element locator is hidden from the page. The
default value is false.
Timeout: The maximum wait time for an element in milliseconds. The default
value is 30000. If the timeout is set to zero, this is discarded.
The default wait time can be modified using the below method:
page.setDefaultTimeout(6000)
For example,
waitForFunction
This method is used to wait till the provided function returns a true value. The syntax is
as follows:
page.waitForFunction(
pagefunction,
{options : value},
pagefunction args
)
This function shall wait till the value of the element with id is equal to text.
117
Puppeteer
The option is an array of waiting parameters. They are - polling (the interval at which
the pagefunction should be executed in milliseconds) and timeout (The maximum time
the Puppeteer shall wait for the pagefunction to return true value).
The pagefunction args are the arguments passed to the pagefunction function.
In the below image, let us input text - Puppeteer and then press Enter.
After pressing Enter, a new window having the search results with text - About 39
results should open up.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
118
Puppeteer
Step 3: Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function waitImplementation(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage()
//launch URL
await page.goto('https://www.tutorialspoint.com/index.htm')
//identify edit box
const f = await page.$("#gsc-i-id1")
//enter text
f.type("Puppeteer")
//wait for sometime
await page.waitForTimeout(4000)
//press Enter
await page.keyboard.press('Enter')
//wait for an element xpath
await page.waitForXPath("//div[@class='gsc-result-info']")
//identify element
const t = await page.$(".gsc-result-info")
//obtain text
const text = await (await t.getProperty('textContent')).jsonValue()
119
Puppeteer
node <filename>
node testcase1.js
120
39. Puppeteer — Capture Screenshot Puppeteer
await page.screenshot({
path: 'tutorialspoint.png'
})
Here, the path where the screenshot is to be saved is passed as a parameter to the
method. With this, only the viewable part of the web page shall be captured. To capture
the full page screenshot, we have to pass another parameter called the fullPage and set
its value to true.
await page.screenshot({
path: 'tutorialspoint.png', fullPage: true
})
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as
follows:
Step 1: Create a new file within the directory where the node_modules folder is created
(location where the Puppeteer and Puppeteer core have been installed).
121
Puppeteer
Right-click on the folder where the node_modules folder is created, then click on the
New file button.
Step 3: Add the below code within the testcase1.js file created.
122
Puppeteer
await p.screenshot({
path: 'tutorialspoint.png'
});
//browser close
await browser.close()
})
node <filename>
node testcase1.js
After the command has been successfully executed, a new file called the
tutorialspoint.png gets created within the page directory. It contains the captured
screenshot of the page launched in the browser.
123