With a playwright, you can handle different types of dropdowns. This article will focus on the basic one, including select and option tags. We will select the value from the dropdown using three techniques value, label, and index.
Table of Contents
1. Demo Website
To practice, visit this link: http://autopract.com/selenium/dropdown1/
<select class="custom-select" style="width:150px;">
<option value="item1">Badminton</option>
<option value="item2">Cricket</option>
<option value="item3">Football</option>
<option value="item4">Table Tennis</option>
</select>
2. selectOption Method
Syntax:
locator.selectOption(values[, options])
page.selectOption(selector, values[, options])
frame.selectOption(selector, values[, options])
- We can select one or more options using this method.
- We can select by value, index, or label using this method.
- It Returns the array of option values that have been successfully selected.
- This method throws an error if the target element is not a <select> element.
- This method waits for actionability checks until all specified options are present in the <select>.
3. Select By Value
The Default option is value. You only need to give the value of the option value attribute as a parameter.
test.only('Dropdown Value', async({page})=>{
await page.goto('http://autopract.com/selenium/dropdown1/')
await page.locator('select.custom-select').selectOption('item2')
})
Here select.custom-select is the selector of the dropdown and item2 is the value of value attribute of Cricket.
4. Select By Label
The label is the value displayed in the dropdown.
await page.locator('select.custom-select').selectOption({ label: 'Table Tennis' })
5. Select By Index
You can also specify the index. Here, the index starts from 0.
await page.locator('select.custom-select').selectOption({ index: 2 })
Here index 2 will select value Football.