Handling Dropdown in Selenium | Select Class in Selenium




Handling dropdowns in Selenium can be done using the Select class. The Select class provides methods to interact with dropdown elements on a web page.


Here are some examples of how to handle dropdowns in Selenium:


1.To select an option by its visible text:


WebElement selectElement = driver.findElement(By.id("selectId"));
Select select = new Select(selectElement);
select.selectByVisibleText("Option 2");


In this example, the findElement(By.id("selectId")) method is used to locate the dropdown element on the page. Then, a new Select object is created using the dropdown element as the parameter. The selectByVisibleText("Option 2") method is then used to select the option with the visible text "Option 2".



2.To select an option by its value:


WebElement selectElement = driver.findElement(By.id("selectId"));
Select select = new Select(selectElement);
select.selectByValue("option2");


In this example, the findElement(By.id("selectId")) method is used to locate the dropdown element on the page. Then, a new Select object is created using the dropdown element as the parameter. The selectByValue("option2") method is then used to select the option with the value "option2".



3.To select an option by its index:


WebElement selectElement = driver.findElement(By.id("selectId"));
Select select = new Select(selectElement);
select.selectByIndex(1);


In this example, the findElement(By.id("selectId")) method is used to locate the dropdown element on the page. Then, a new Select object is created using the dropdown element as the parameter. The selectByIndex(1) method is then used to select the option at index 1.


4.To deselect an option:


WebElement selectElement = driver.findElement(By.id("selectId"));
Select select = new Select(selectElement);
select.deselectByVisibleText("Option 2");



In this example, the findElement(By.id("selectId")) method is used to locate the dropdown element on the page. Then, a new Select object is created using the dropdown element as the parameter. The deselectByVisibleText("Option 2") method is then used to deselect the option with the visible text "Option 2".



It's important to note that when working with dropdowns, it's important to check the type of the select element(single select or multiple select) before interacting with it. Also, it's important to use try-catch block to handle the NoSuchElementException that could be thrown if an option is not present

Post a Comment

Post a Comment (0)

Previous Post Next Post