100% found this document useful (1 vote)
138 views

Puppeteer Tutorial

Puppeteer tutorial
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
138 views

Puppeteer Tutorial

Puppeteer tutorial
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 128

Puppeteer

i
Puppeteer

About the Tutorial


Puppeteer is used for automation and streamlining of the frontend development and
testing respectively. This tutorial shall give us a thorough insight on Puppeteer and its
different terminologies. The tutorial contains practical examples on all main topics.

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.

Copyright & Disclaimer


 Copyright 2021 by Tutorials Point (I) Pvt. Ltd.

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

Copyright & Disclaimer ..................................................................................................................................... i

Table of Contents ............................................................................................................................................ ii

1. Puppeteer – Introduction.......................................................................................................................... 1

Puppeteer Architecture ................................................................................................................................... 2

2. Puppeteer — Element Handling ................................................................................................................ 3

Puppeteer Methods to Locate Elements ......................................................................................................... 3

Types of Locators ............................................................................................................................................. 4

3. Puppeteer — Usage of Google .................................................................................................................. 5

4. Puppeteer — Installation of NodeJS.......................................................................................................... 6

5. Puppeteer — VS Code Configuration....................................................................................................... 10

6. Puppeteer — Installation ........................................................................................................................ 12

7. Puppeteer — Basic Test on Puppeteer .................................................................................................... 15

8. Puppeteer — Non Headless Execution .................................................................................................... 17

9. Puppeteer — Comparison between Puppeteer and Selenium................................................................. 20

10. Puppeteer — Comparison between Puppeteer and Protractor ............................................................... 22

11. Puppeteer — Comparison between Puppeteer and Cypress ................................................................... 24

12. Puppeteer — Browser Operations .......................................................................................................... 26

13. Puppeteer — Handling Tabs .................................................................................................................... 28

14. Puppeteer — Basic Commands ............................................................................................................... 31

15. Puppeteer with Firefox ........................................................................................................................... 34

16. Puppeteer with Chrome .......................................................................................................................... 37

17. Puppeteer — Handling Confirm Alerts .................................................................................................... 39

18. Puppeteer — Handling Drop-downs........................................................................................................ 42

ii
Puppeteer

Methods to Handle Dropdown ...................................................................................................................... 42

19. Puppeteer — Locators ............................................................................................................................ 45

Methods to locate elements ......................................................................................................................... 45

Types of Locators ........................................................................................................................................... 46

20. Puppeteer — Xpath Functions ................................................................................................................ 51

21. Puppeteer — Xpath Attributes ................................................................................................................ 55

22. Puppeteer — Xpath Grouping ................................................................................................................. 59

23. Puppeteer — Absolute Xpath.................................................................................................................. 63

24. Puppeteer — Relative Xpath ................................................................................................................... 67

25. Puppeteer — Xpath Axes ........................................................................................................................ 70

26. Puppeteer — Type Selector..................................................................................................................... 73

27. Puppeteer — Name Selector and Class Name Selector ........................................................................... 76

Name Selector ............................................................................................................................................... 76

Class Name Selector ...................................................................................................................................... 78

28. Puppeteer — Id Selector ......................................................................................................................... 81

29. Puppeteer — Attribute Selector .............................................................................................................. 84

30. Puppeteer — Handling Links/Button....................................................................................................... 87

31. Puppeteer — Handling Edit Boxes and Checkboxes ................................................................................ 90

Handling Edit Boxes ....................................................................................................................................... 90

Handling Checkboxes..................................................................................................................................... 92

32. Puppeteer — Handling Frames ............................................................................................................... 96

33. Puppeteer — Keyboard Simulation ......................................................................................................... 99

Keyboard Methods ........................................................................................................................................ 99

34. Puppeteer — Getting Element Text....................................................................................................... 102

35. Puppeteer — Getting Element Attribute ............................................................................................... 105

Methods for Element Attribute ................................................................................................................... 105

36. Puppeteer — Device Emulation ............................................................................................................ 109

37. Puppeteer — Disable JavaScript............................................................................................................ 114


iii
Puppeteer

38. Puppeteer — Synchronization............................................................................................................... 116

Synchronization methods ............................................................................................................................ 116

39. Puppeteer — Capture Screenshot ......................................................................................................... 121

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.

Puppeteer is not considered as an automation tool like Selenium, Cypress, Protractor,


and so on. It is mostly used to manage the internal features of the Chromium browser.
We can open DevTools in the Chrome browser, by pressing F12 or
Command+Option+C(in MacOS).

Puppeteer is like a development tool as it is capable of performing a majority of tasks


performed by a developer like handling requests and responses, locating elements,
network traffic and performance, and so on.

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.

Puppeteer has the below hierarchy:

 Browser(with/without headless mode): The browser performs the actions to


be executed on the browser engine.
 Chromium Development Project or CDP: The Chromium is the real place
where all the operations are executed. The browsers - Microsoft Edge and Chrome
utilise Chromium as browser engine.
 Puppeteer: This is actually a package based on the node module.
 Automation test code: This is also known as the Nodejs level. Here, the actual
automation code is developed by the end-user using JavaScript.

2
2. Puppeteer — Element Handling Puppeteer

We can handle elements on page with Puppeteer. 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. 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.

Puppeteer Methods to Locate Elements


These methods are listed below:

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.

The ElementHandle methods like elementHandle.$, elementHandle.$$ and


elementHandle.$x can be applied to an element. In that case, an element shall be
searched within the DOM of the present ElementHandle and not in the entire DOM.

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:

const n = await page.$(".heading")

To identify it using the ElementHandle method on an element, the expression should be


as follows:

const m = await page.$("ul")


const p = await m.$(".heading")

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 usages are listed below:

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

The steps to configure NodeJS are listed below:

Step 1: Launch the application having the below link:

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

Step 4: Agree to the terms of agreement of Nodejs.

7
Puppeteer

Step 5: Click on Install.

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:

Step 1: Navigate to the below link:

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 steps for installation of Puppeteer are listed below:

Step 1: Install NodeJS.

The details on how to install NodeJs is discussed in detail in the Chapter of Installation of
NodeJS.

Step 2: Create an empty folder, say puppeteer in a location.

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

Step 5: For Puppeteer installation, run the below mentioned command:

npm install puppeteer

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

Step 3: Add the below code in this file:

//adding Puppeteer library


const pt = require('puppeteer');
pt.launch().then(async browser => {

15
Puppeteer

//browser new page


const p = await browser.newPage();
//set viewpoint of browser page
await p.setViewport({ width: 1000, height: 500 })
//launch URL
await p.goto('https://www.tutorialspoint.com/index.htm')
//capture screenshot
await p.screenshot({
path: 'tutorialspoint.png'
});
//browser close
await browser.close()
})

Step 4: Execute the code with the following command:

node <filename>

So in our example, we shall run the following command:

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

17
Puppeteer

Step 3: Add the below code within the testcase1.js file created.

//adding Puppeteer library


const pt = require('puppeteer');
//adding headless flag to false
pt.launch({headless:false}).then(async browser => {
//browser new page
const p = await browser.newPage();
//set viewpoint of browser page
await p.setViewport({ width: 1000, height: 500 })
//launch URL
await p.goto('https://www.tutorialspoint.com/about/about_careers.htm');
})

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the below mentioned command:

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

Puppeteer and Selenium

The major differences between Puppeteer and Selenium are given below:

Sr. No. Puppeteer Selenium

1. Puppeteer is developed mainly for Selenium can be used to execute tests


Chromium so the tests developed are on multiple browsers like Chrome,
mainly executed in Chrome. Firefox, IE, Safari, and so on.

2. Puppeteer code can be implemented Selenium code can be implemented on


only in JavaScript. multiple languages like Java, Python,
JavaScript, C#, and so on.

3. Puppeteer provides APIs to manage Selenium requires additional external


headless execution in Chrome by browser drivers that trigger tests as
using the DevTools protocol. per the user commands.

4. Puppeteer manages the Chrome Selenium is primarily used to execute


browser. tests to automate the actions
performed on the browser.

5. Puppeteer is faster in executing tests Selenium is slower in executing tests


than Selenium. than Puppeteer.

6. Puppeteer is a module in node Selenium is a dedicated test


developed for Chromium engine. automation tool.

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.

9. Puppeteer can be used to work on the Selenium cannot be used to work on


majority of features in the DevTools in the majority of features in the
the Chrome browser. DevTools in the Chrome browser.

10. Puppeteer can be used to execute Using an emulator with Selenium is


tests on various devices with the help not easy.
of the emulators.

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.

12. Puppeteer can be used to save a Selenium can be used to save a


screenshot in both image and PDF screenshot in both image and PDF
formats. formats only in the Selenium 4
version.

13. Puppeteer was first introduced in the Selenium was first introduced in the
year 2017. year 2004.

14. In Puppeteer, we can verify an In Selenium, we can verify an


application without image loading. application without image loading.

21
10. Puppeteer — Comparison between Puppeteer

Puppeteer and Protractor

The major differences between Puppeteer and Protractor are given below:

Sr. No. Puppeteer Protractor

1. Puppeteer is a module in node Protractor is a dedicated test


developed for Chromium engine. automation tool.

2. Puppeteer is faster in executing tests Protractor is slower in executing tests


than Protractor. than Puppeteer.

3. Puppeteer is developed mainly for Protractor can be used to execute


Chromium so the tests developed are tests on multiple browsers like
mainly executed in Chrome. Chrome, Firefox, IE, Safari, and so
on.

4. Puppeteer can be used for API testing API testing with Protractor is difficult.
by utilising the requests and the
responses.

5. Puppeteer can be used to verify the Protractor cannot be used to verify


count of CSS and JavaScript files the count of CSS and JavaScript files
utilised for loading a webpage. utilised for loading a webpage.

6. Puppeteer can be used to work on the Protractor cannot be used to work on


majority of features in the DevTools in the majority of features in the
the Chrome browser. DevTools in the Chrome browser.

7. Puppeteer can be used to execute Using an emulator with Protractor is


tests on various devices with the help not easy.
of the emulators.

8. Puppeteer can be used to save a Protractor can be used to save a


screenshot in both image and PDF screenshot in only image format.
formats.

9. Puppeteer can be used to obtain the Protractor cannot be used to obtain


time needed for a page to load. the time needed for a page to load.

10. In Puppeteer, we can verify an In Protractor, we can verify an


application without image loading. application without image loading.

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

Puppeteer and Cypress

The major differences between Puppeteer and Cypress are as follows:

Sr. No. Puppeteer Cypress

1. Puppeteer is a module in node Cypress is a dedicated test automation


developed for Chromium engine. framework developed in JavaScript.

2. Puppeteer is mainly used for web Cypress is mainly used to automate


page scraping and crawling test cases for a complete application.
SPA(Single Page Application).

3. Assertions in Puppeteer are based Cypress has its individual assertions.


on the Mocha, Jasmine or Jest
frameworks.

4. VS Code and Webstorm are mostly Cypress has its individual IDE.
used as an IDE for Puppeteer.

5 Puppeteer is developed mainly for Cypress can be used to execute tests


Chromium so the tests developed on multiple browsers like Chrome,
are mainly executed in Chrome. Firefox, Electron and so on.

6. Puppeteer has no dashboard. Cypress has its dashboard to see the


recorded tests and gives us detail on
the events that took place during
execution.

7. Puppeteer is faster in executing Cypress is slower in executing tests


tests than Cypress. than 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.

10. Puppeteer has no features of Cypress has the features of fixtures


fixtures and group fixtures in tests. and group fixtures applied in tests.

24
Puppeteer

11. Grouping of tests for execution Grouping of tests for execution can be
cannot be done in Puppeteer. done in Cypress.

12. Puppeteer has no mocking Cypress has the mocking capabilities.


capabilities.

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:

let l = await puppeteer.launch({product : "chrome" })

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:

let l = await puppeteer.launch({headless : false})

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:

let l = await puppeteer.launch({devtools: true})

defaultViewport: This is of type object. It provides a persistent viewport for a


page(default value of viewport is 800*600). We can modify the size of the viewport by
mentioning integer values in width and height for pixels. The syntax is as follows:

let l = await puppeteer.launch({defaultViewport: { width: 500, height: 459}})

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:

let l = await puppeteer.launch({slowMo: 500})

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

We can handle tabs in Puppeteer using the below methods:

newPage()
We can open a new tab using this method available in the browser object. The syntax is
as follows:

const p = await browser.newPage()

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.


28
Puppeteer

Step 3: Add the below code within the testcase1.js file created.

//adding Puppeteer library


const pt = require('puppeteer')
pt.launch().then(async browser => {
//browser new page
const p = await browser.newPage();
//set viewpoint of browser page
await p.setViewport({ width: 1000, height: 500 })
//launch URL
await p.goto('https://www.tutorialspoint.com/index.htm')
//capture screenshot
await p.screenshot({
path: 'tutorialspoint.png'
});
//browser close
await browser.close()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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

Some of the basic commands of Puppeteer are listed below:

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

31
Puppeteer

Step 3: Add the below code within the testcase1.js file created.

//adding Puppeteer library


const pt = require('puppeteer');
pt.launch().then(async browser => {
//browser new page
const p = await browser.newPage();
//set viewpoint of browser page
await p.setViewport({ width: 1000, height: 500 })
//launch URL
await p.goto('https://www.tutorialspoint.com/questions/index.php')
//obtain page title
console.log("Page title: " + await p.title())
//obtain URL
console.log("Url: " + await p.url())
//browser close
await browser.close()
})

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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:

npm install puppeteer-firefox

Also, we have to add the Firefox-Puppeteer library in the code.

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

34
Puppeteer

Step 2: Enter a filename, say testcase1.js.

Step 3: Add the below code within the testcase1.js file created.

//adding Puppeteer- Firefox library


const pt = require('puppeteer-firefox');
//adding headless flag to false
pt.launch().then(async browser => {
//browser new page
const p = await browser.newPage();
//set viewpoint of browser page
await p.setViewport({ width: 1000, height: 500 })
//launch URL
await p.goto('https://www.tutorialspoint.com/about/about_careers.htm')
//get browser
const v = await p.browser().version();
console.log("Browser: " + v)
//browser close

35
Puppeteer

await browser.close()
})

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

Step 3: Add the below code within the testcase1.js file created.
37
Puppeteer

//adding Puppeteer library


const pt = require('puppeteer');
pt.launch().then(async browser => {
//browser new page
const p = await browser.newPage();
//set viewpoint of browser page
await p.setViewport({ width: 1000, height: 500 })
//launch URL
await p.goto('https://www.tutorialspoint.com/index.htm')
//get browser
const v = await p.browser().version();
console.log("Browser: " + v)
//browser close
await browser.close()
})

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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

Puppeteer is capable of handling Alerts. The automation tools like Selenium,


WebdriverIO, and so on, accept or dismiss an alert after it has appeared on the page.

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.

Methods for Handling Confirm Alerts


Some methods to work with Alerts are listed below:

 accept(): Promise<void> - This method is used to accept an alert.


 message(): string - This method is used to yield the message obtained in an
alert.
 type(): DialogType - This method is used to obtain the Dialog type. A Dialog
type can be a prompt, confirm or prompt.
 dismiss(): Promise<void> - This method is used to dismiss an alert.

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

39
Puppeteer

Step 2: Enter a filename, say testcase1.js.

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()

Step 4: Execute the code with the following command

node <filename>

So in our example, we shall run the command given below:

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.

Methods to Handle Dropdown


Some methods to work with static dropdowns:

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:

const page = await browser.newPage()


const f = await page.$('[name="selType"]')
await f.select("subject")

We can also select multiple options from a multi-select dropdown. The syntax is as
follows:

await f.select("subject", "name")

To obtain select value from the dropdown, we have to use the getProperty method and
pass value as a parameter to this field.

const v = await (await n.getProperty("value")).jsonValue()


console.log(v)

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:

const page = await browser.newPage()

42
Puppeteer

const f = await page.$('[name="selType"]')


await f.type("subject")

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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

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 dropdown then select an option by value
const f = await page.$('[name="selType"]')
await f.select("subject")
//wait for sometime
await page.waitForTimeout(4000)
//get value selected
const v = await (await f.getProperty("value")).jsonValue()
console.log(v)
}
dropDownHandle()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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

We can handle elements on page with Puppeteer. 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. 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.

Methods to locate elements


These methods are listed below:

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.

The ElementHandle methods like elementHandle.$, elementHandle.$$ and


elementHandle.$x can be applied to an element. In that case, an element shall be
searched within the DOM of the present ElementHandle and not in the entire DOM.

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:

const n = await page.$(".heading")

To identify it using the ElementHandle method on an element, the expression should be:

const m = await page.$("ul")


const p = await m.$(".heading")

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.

Let us take an example of an element having the below html code:

47
Puppeteer

We can identify the first checkbox in the above image, with the expression:

const n = await page.$("input[type='checkbox']")

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.
48
Puppeteer

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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

//wait for sometime


await page.waitForTimeout(4000)
//verify if checkbox is checked
const v = await (await n.getProperty("checked")).jsonValue()
console.log(v)
}
checkBoxHandle()

Step 4: Execute the code with the below mentioned command:

node <filename>

So in our example, we shall run the following command:

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.

The syntax for the use of text() function is as follows:

//tagname[text()='visible text on element']

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.

The syntax for the use of contains() function is as follows:

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

The syntax for the use of starts-with() function is as follows:

//tagname[starts-with(text(),'visible text on element')

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

The xpath for the element shall be //*[text()='Library'].

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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' and @attribute2='value2']

The format for writing an xpath with OR condition is as follows:

//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

The xpath for the element shall be as follows:

//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).

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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.

The syntax for the use of function last() is as follows:

(/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.

So the xpath expression shall be as follows:

//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).

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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

The absolute xpath for the logo is as follows:

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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()

Step 4: Execute the code with the command mentioned below:

node <filename>

So in our example, we shall run the following command:

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.

To obtain a relative path by an attribute, the xpath expression is as follows:

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

The relative xpath for the element is given below:

//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).

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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

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())
}
selectorRelativeXpath()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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.

So the xpath expression shall be as follows:

//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).

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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

const page = await browser.newPage()


//launch URL

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()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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

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

The syntax for type selector is as follows:

const n = await page.$("h4")

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

73
Puppeteer

Step 2: Enter a filename, say testcase1.js.

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()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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

Let us begin by learning about name 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.

The syntax for name selector is as follows:

const f = await page.$('[name="search"]')

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

76
Puppeteer

Step 2: Enter a filename, say testcase1.js.

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

//wait for sometime


await page.waitForTimeout(4000)

//browser close
await browser.close()
}
selectorName()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

node testcase1.js

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

The syntax for class name selector is as follows:

const n = await page.$(".txtloc")

In the below example, let us identify the highlighted element having class name heading
and obtain its text - About Tutorialspoint.

The id selector expression for the above element shall be .heading.

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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

const page = await browser.newPage()


//launch URL

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()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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

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

The syntax for Id selector is as follows:

const n = await page.$("#loc")

In the below example, let us identify the highlighted element having id txtSearchText
and enter text into it.

The id selector expression for the above element shall be #txtSearchText.

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

81
Puppeteer

Step 2: Enter a filename, say testcase1.js.

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

//wait for sometime


await page.waitForTimeout(4000)

//browser close
await browser.close()
}
selectorId()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

node testcase1.js

83
29. Puppeteer — Attribute Selector Puppeteer

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

The syntax for attribute selector is as follows:

const f = await page.$("ul[name='val']")

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

84
Puppeteer

Step 2: Enter a filename, say testcase1.js.

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

console.log("Obtained text is: " + t)


}

selectorAttribute()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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

Puppeteer is capable of handling a link/button on a page. Before clicking an element we


must be able to uniquely identify it with the help of any of the locators. In Puppeteer, we
can click an element only if its dimensions are greater than zero pixel.

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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

Let us understand how Puppeteer can handle edit boxes.

Handling Edit Boxes


Puppeteer is capable of handling edit boxes. An edit box has an HTML tag as input and
its type attribute is set to the value as text.

Some methods to work with edit boxes are listed below:

type()
This method is used to input text into an edit box and text area without replacing the
already present content.

The syntax for type() is as follows::

const n = await page.$("#txt")


await n.type("Puppeteer")

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.

The syntax for the same is as follows:

await page.type("[class='loc']", "Tutorialspoint", {delay:700})

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.

The syntax is given below:

const n = await page.$("#txt")


await n.type("Puppeteer")
await n.click({clickCount: 3});
await page.keyboard.press('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.

const v = await (await n.getProperty("value")).jsonValue()


console.log(v)

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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

Some methods to work with checkboxes are given below:

click()
It is used to check and uncheck a checkbox. This method is a part of the ElementHandle
class.

The syntax of click() is as follows:

const n = await page.$("#txt")


n.click()

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

const v = await (await n.getProperty("checked")).jsonValue()


console.log(v)

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

Step 3: Add the below code within the testcase1.js file created.

//Puppeteer library

94
Puppeteer

const pt= require('puppeteer')


async function checkBoxHandle(){
//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/checkboxes')
//identify element then click
const n = await page.$("input[type='checkbox']")
n.click()
//wait for sometime
await page.waitForTimeout(4000)
//verify if checkbox is checked
const v = await (await n.getProperty("checked")).jsonValue()
console.log(v)
}
checkBoxHandle()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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.

The syntax to handle frames is as follows:

const f = await page.$("frame[name='frame-bottom']")


const m = await f.contentFrame()

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

96
Puppeteer

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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();

//identify element inside frame


const n = await x.$("body")
//get text
const v = await (await n.getProperty("textContent")).jsonValue()
console.log(v)
}
frameHandle()

Step 4: Execute the code with the command:

node <filename>

So in our example, we shall run the command:

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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.

The syntax of getting element text is as follows:

const n = await page.$("#txt")


const t = await (await n.getProperty('textContent')).jsonValue()

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

102
Puppeteer

Step 2: Enter a filename, say testcase1.js.

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

console.log("Text is: " + text)


}

getText()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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.

Let us take an example of an edit box having the below 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 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.

Methods for Element Attribute


The ways to obtain an element attribute are listed below:

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:

let v = await page.$eval("input",


element=> element.getAttribute("class"))

element.<attribute name>
The syntax is as follows:

let v = await page.$eval("input",


element=> element.class)

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:

const n = await page.$("#txt")


const t = await (await n.getProperty('textContent')).jsonValue()

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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.

Then, click on the Toggle Device Toolbar.

Click on the dropdown - Responsive to get the list of devices.

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:

const m = puppeteer.devices['iPhone X']


//emulate iPhoneX
await page.emulate(m)

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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

const page = await browser.newPage()


//set device to iPhone X
const m = puppeteer.devices['iPhone X']
//emulate iPhoneX
await page.emulate(m)
//launch URL
await page.goto('https://www.tutorialspoint.com/index.htm')
//capture screenshot of emulated device
await page.screenshot({ path: 'iPhoneDevice.png'})
//browser close
await browser.close()
})

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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 => {

//browser new page


const page = await browser.newPage()
//monitor requests
await page.setRequestInterception(true)
//check resourceType is script
page.on('request', request => {
if (request.resourceType() === 'script')
request.abort();
else
request.continue();
})
//launch application
await page.goto('https://www.tutorialspoint.com/index.htm')
//browser close
await browser.close()
})

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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,

let l = await page.waitForSelector( "#ltxt", { visible: true } )

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,

let x= await page.waitForXPath( "//*[@name='search']", { visible: true } )

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
)

The waitForFunction has the following parameters:

The pagefunction is the function to be executed. For example,

page.waitForFunction("document.getElementById('txt').value === 'text'", {})

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

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

console.log("Text is: " + text)


}
waitImplementation()

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

node testcase1.js

120
39. Puppeteer — Capture Screenshot Puppeteer

We can capture screenshots while working on automation tests developed in Puppeteer


using the screenshot method. A screenshot is generally captured if we encounter an
application error, a failure in a test case, and so on.

The syntax to capture screenshot in Puppeteer is as follows:

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.

The syntax is as follows:

await page.screenshot({
path: 'tutorialspoint.png', fullPage: true
})

Let us capture the screenshot of the below page:

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

The details on Puppeteer installation is discussed in the Chapter of Puppeteer


Installation.

Right-click on the folder where the node_modules folder is created, then click on the
New file button.

Step 2: Enter a filename, say testcase1.js.

Step 3: Add the below code within the testcase1.js file created.

//adding Puppeteer library


const pt = require('puppeteer');
pt.launch().then(async browser => {
//browser new page
const p = await browser.newPage();
//set viewpoint of browser page
await p.setViewport({ width: 1000, height: 500 })
//launch URL
await p.goto('https://www.tutorialspoint.com/index.htm')
//capture screenshot

122
Puppeteer

await p.screenshot({
path: 'tutorialspoint.png'
});
//browser close
await browser.close()
})

Step 4: Execute the code with the command given below:

node <filename>

So in our example, we shall run the following command:

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

You might also like