How To Handle Bootstrap DropDown In Java Selenium With Example Program?

How To Handle Bootstrap Drop Down In Java Selenium With Example Program?

package com.selenium.mix;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.python.modules.thread.thread;
public class BootstrapDropDown 
{
   public static void main(String[] args) throws InterruptedException 
   {
      WebDriver driver=new FirefoxDriver();
      driver.manage().window().maximize();
      driver.get("G:\\Testing_Utilities\\Selenium_Practice\\BootstrapDropdown.html");
      driver.manage().timeouts().implicitlyWait(5000, TimeUnit.SECONDS);
      driver.findElement(By.id("menu1")).click();
      List<WebElement> li=driver.findElements(By.xpath(".//ul[@class='dropdown-menu']/li/a"));
      for(WebElement el:li)
      {
         if(el.getText().equals("CSS"))
         {
            el.click();
            Thread.sleep(3000);
            System.out.println("Element Clicked");
            break;
         }
         System.out.println(el.getText());
      }
   }
}

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

1 thought on “How To Handle Bootstrap DropDown In Java Selenium With Example Program?”

  1. Hi,
    In the above same scenario I want to click all options under the bootstrap dropdown but for my case first condition under for loop is working but when I try to click for second option in that dropdown then stale element exception is throwing. My code is –

    driver.findElement(By.xpath(“xxx”).click(); //click on drop down
    List listOfOptions = driver.findElements(By.xpath(“/html/body/div[5] /div/table/tbody/tr/td/div/table/tbody/tr/td”));

    int NumberOfOptions = listOfOptions.size();

    for(int i=1;i<NumberOfOptions;i++){

    if(listOfOptions.get(i).getText() .contains("Dog")) {

    listOfOptions.get(i).click();
    break;
    }
    }
    driver.findElement(By.xpath("xxx").click(); // clicking the dropdown again to show the options

    for(int i=1;i<NumberOfOptions;i++){

    if(listOfOptions.get(i).getText().contains("Cat")){

    listOfOptions.get(i).click(); // here getting the stale element exception
    break;
    }
    }
    ================
    I am not sure my code is correct or not. Please help me.

    Reply

Leave a Comment