Puppeteer – Id Selector


Puppeteer – Id 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. 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.

Syntax

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.


Tutor Connect

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.


Node Modules

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


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

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *