Automate drop-down menu and checkbox using Selenium 4.0

Reading Time: 3 minutes

In the last blog, we saw how we can use locator strategies to find and use different elements for automating our projects. In this blog, we will see how we can automate the drop-down menu and checkbox using selenium 4.0.

What’s the need for automating drop-down menu and checkbox?

  • Nowadays most websites contain drop-down menus and check boxes to perform various interactions with the website.
  • These can be static and can also be dynamic. Which may change according to the input that the user provides.
  • So, it is important to know how to handle these cases

Static drop-down menu

  • These drop-down menus contain the static values inside them. They don’t change with input from the user.
  • These are easy to handle and locate.
public class SeleniumStaticDropDownTest {
    public static void main(String[] args){
    System.setProperty("webdriver.chrome.driver", "/home/ankur/Documents/Selenium/chromedriver");
    WebDriver driver = new ChromeDriver();

    driver.get("https://rahulshettyacademy.com/dropdownsPractise/");

        WebElement staticDropdown = driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency"));

        Select dropdown = new Select(staticDropdown);
        //Initialize the driver
        dropdown.selectByIndex(3);
// select dropdown item using it's index value
        System.out.println(dropdown.getFirstSelectedOption().getText());
        dropdown.selectByVisibleText("AED");
// select dropdown item using its text
        System.out.println(dropdown.getFirstSelectedOption().getText());
        dropdown.selectByValue("INR");
// select dropdown item using value attribute
        System.out.println(dropdown.getFirstSelectedOption().getText());
// Extracts and prints selected value from the drop-down menu
        // driver.close();

    }
}

Dynamic drop-down menu

  • In some cases, the values for the second drop-down is dependent upon the first drop-down menu.
  • In this case, the second drop-down elements will not be visible until we provide a valid input in the first drop-down.
public class SeleniumDynamicDropDownTest {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "/home/ankur/Documents/Selenium/chromedriver");
        WebDriver driver = new ChromeDriver();

        driver.get("https://rahulshettyacademy.com/dropdownsPractise/");
        driver.findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click();
    // Click to open the drop-down menu
        driver.findElement(By.xpath("//a[@value='BLR']")).click();
    // Select the value using xpath from the first drop-down menu
        driver.findElement(By.xpath("(//a[@value='MAA'])[2]")).click();
    // Select the value using xapth from the second drop-down menu
    //    driver.findElement(By.xpath("//*[@id=\"dropdownGroup1\"]/div/ul[2]/li[7]/a[2]")).click();
         driver.close();

    }
}

Selecting drop-down items using loop

  • Drop-down menus sometimes contain items whose value can be incremented or decremented.
  • In this scenario to select or increment the value, we need to hit the same button multiple times.
  • This can be achieved using two ways. First is writing the same line of code multiple times or you can write a loop for that.
public class SeleniumDropDownLoopingTest {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "/home/ankur/Documents/Selenium/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://rahulshettyacademy.com/dropdownsPractise/");
        driver.findElement(By.id("divpaxinfo")).click();
        // Selecting dropdown menu
        driver.findElement(By.id("hrefIncAdt")).click();
        // Selecting and clicking on plus button once
        System.out.println(driver.findElement(By.id("divpaxinfo")).getText());
        // print the selected number of people
        for (int i=1;i<2;i++){
            driver.findElement(By.id("hrefIncAdt")).click();
        }
        // For loop to click plus button twice
       driver.findElement(By.id("btnclosepaxoption")).click();
       // Click on done
        System.out.println(driver.findElement(By.id("divpaxinfo")).getText());
        // print the selected number of people
         driver.close();

    }
}

Auto suggestive drop-down menu

  • These types of drop-box generates the value according to the user’s input.
  • This drop-box is usually blank but when you enter some input like in a search box suggestions get displayed.
  • We cannot interact with an element until it is not visible, So, if it is not visible the test will fail.
public class SeleniumAutoSuggestiveDropDownTest {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "/home/ankur/Documents/Selenium/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://rahulshettyacademy.com/dropdownsPractise/");
        driver.findElement(By.id("autosuggest")).sendKeys("ind");
        // Select the auto suggest drop-box and enter the value
        List<WebElement> options = driver.findElements(By.cssSelector("li[class='ui-menu-item'] a"));
        // Storing the result from the auto suggest in a list
        for(WebElement option :options){
            if (option.getText().equalsIgnoreCase("india"))
        // Search for the required value from the list and store it    
            {
                option.click();
        // Select the stored element        
                break;
            }
        }
         driver.close();
    }
}

Checkbox

  • Checkboxes are used when we want to take single or multiple inputs from the user.
  • These elements are always visible and can be uniquely identified using locators.
public class SeleniumCheckboxTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/home/ankur/Documents/Selenium/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://rahulshettyacademy.com/dropdownsPractise/");
        driver.findElement(By.cssSelector("input[id='ctl00_mainContent_chk_friendsandfamily']")).click();
        // Find and select the required checkbox
        System.out.println(driver.findElement(By.cssSelector("input[id='ctl00_mainContent_chk_friendsandfamily']")).isSelected());
        // Check that the checkbox is selected or not
        driver.close();

    }
}
  • This is a small introduction to automate the drop-down menu and checkbox using selenium 4.0. In the next blog, we will see how we can put assertions in our tests.

References

Techhub template


Knoldus-blog-footer-image

Written by 

Ankur is a Sr. QA Consultant having experience of more than 3 years. He is familiar with the core concepts of manual and automation, postman and Newman are his expertise. He is always eager to learn new and advanced concepts in order to expand his horizon and apply them in project development with his existing knowledge. His hobbies include watching web series and getting to know about all the latest gadgets that come in the market.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading