Handle Bootstrap Dropdown in Selenium

What is Bootstrap?
Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

Refer below links to know more about bootstrap.
https://www.w3schools.com/bootstrap/default.asp
https://getbootstrap.com/docs/4.0/components/dropdowns/

Bootstrap dropdown
Bootstrap dropdown is not like traditional dropdowns as it doesn't use <select> tags, rather it uses <ul> and <li> tags to make a dropdown.

Bootstrap Dropdown UI

Inspecting Bootstrap Dropdown
So to handle bootstrap dropdown, you need to use findElements() method which will return all the options of the dropdown.
Following code shows how to handle a bootstrap dropdown in Selenium WebDriver:

public class BootstrapDropDown {



     public static void main(String[] args) throws InterruptedException {

         

          WebDriver driver;

          System.setProperty("webdriver.chrome.driver","C:\\Users\\Hitendra\\Downloads\\chromedriver_win32 (1)\\chromedriver.exe");

          driver = new ChromeDriver();

          driver.manage().window().maximize();

          driver.get("https://www.automationtestinginsider.com/2019/12/bootstrap-dropdown-example_12.html");

          Thread.sleep(2000);

         

          driver.findElement(By.xpath("//button[@id='bootstrapmenu']")).click();

         

          List <WebElement> options=driver.findElements(By.xpath("//ul[@class='dropdown-menu']//li/a"));

         

          for(WebElement ele:options) {

             

              String value=ele.getText();

              System.out.println(value);

             

              if(value.equalsIgnoreCase("contact us")) {

                   ele.click();

                   break;

              }

          }

         

          Thread.sleep(2000);

          driver.close();

     }

}




Please watch below youtube video for detail explanation:



No comments:

Post a Comment