Code on how to select from a drop down in Selenium using java –Standard HTML without JavaScript
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class DropdownHandler {
private WebDriver driver;
public DropdownHandler(WebDriver driver) {
this.driver = driver;
}
public void selectFromDropdown(By locator, String visibleText) {
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement dropdownElement = wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
Select dropdown = new Select(dropdownElement);
dropdown.selectByVisibleText(visibleText);
}
public void fillForm() {
// Example usage:
selectFromDropdown(By.id("country"), "United States");
selectFromDropdown(By.name("state"), "California");
selectFromDropdown(By.cssSelector(".city-dropdown"), "Los Angeles");
}
}
For code which has JavaScript use the following method
public void selectFromCustomDropdown(By dropdownLocator, By optionLocator) {
WebDriverWait wait = new WebDriverWait(driver, 10);
// Click to expand the dropdown
WebElement dropdown = wait.until(ExpectedConditions.elementToBeClickable(dropdownLocator));
dropdown.click();
// Select the desired option
WebElement option = wait.until(ExpectedConditions.visibilityOfElementLocated(optionLocator));
option.click();
}
public void fillFormWithCustomDropdowns() {
// Example usage with custom dropdowns
selectFromCustomDropdown(By.id("custom-dropdown"), By.xpath("//li[text()='Option 1']"));
selectFromCustomDropdown(By.id("custom-dropdown"), By.xpath("//li[text()='Option 2']"));
}
Add the following libraries to be able to use the above method
Selenium WebDriver: The core Selenium library for automation.
WebDriverWait: For handling synchronization and waiting for elements.
Select Class: Specifically designed for interacting with <select> elements.