English 中文(简体)
Puppeteer - Handling Drop-downs
  • 时间:2024-11-03

Puppeteer - Handpng Drop-downs


Previous Page Next Page  

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.

Command has been Successfully

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.

Syntax

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.

Syntax

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.

Syntax

The syntax is as follows −


const page = await browser.newPage()
   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-cpck on the folder where the node_modules folder is created, then cpck 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 pbrary
const pt= require( puppeteer )
async function dropDownHandle(){
   //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 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
Terminal Command

After the command has been executed successfully, the value of the option selected in the dropdown - subject is printed in the console.

Advertisements