How to Handle Bootstrap Dropdown in Selenium WebDriver

Have u ever heard about handle Bootstrap dropdown in Selenium? If no, then today you will learn 2 new things today.

First one – What is bootstrap dropdown

The second one- How to Select values from the bootstrap dropdown.

We already have discussed how to work with traditional dropdowns and we have also explored multiple ways to handle the same but today we will see how to work with Boot Strap dropdown.

The bootstrap dropdown is enhanced part of dropdown where you will deal with UL and LI tag of HTML.



An example of Bootstrap dropdown is below.

To handle this kind of drop-down we have to use findElements method and then we can run a for loop to get specific elements.

Program to handle bootstrap dropdown in Selenium Webdriver

package qaearth;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.qaearth.automation.utilities.Constantns;
public class BootStrap {
public static void main(String[] args) throws InterruptedException {
// Start firefox browser
System.setProperty("webdriver.chrome.driver", "Drivers/chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
// start the application
driver.get("https://qaearth.blogspot.in/2017/12/how-to-handle-bootstrap-dropdown-in.html");
// First we have to click on menu item then only dropdown items will
// display
driver.findElement(By.xpath(".//*[@id='menu1']")).click();
// adding 2 seconds wait to avoid Sync issue
Thread.sleep(2000);
// Dropdown items are coming in <a> tag so below xpath will get all
// elements and findElements will return list of WebElements
List<WebElement> list = driver.findElementsByXPath("//ul[@class='dropdown-menu']//li/a");
// We are using enhanced for loop to get the elements
for (WebElement ele : list)
{
// for every elements it will print the name using innerHTML
System.out.println("Values " + ele.getAttribute("innerHTML"));
// Here we will verify if link (item) is equal to Java Script
if (ele.getAttribute("innerHTML").contains("Selenium")) {
// if yes then click on link (iteam)
ele.click();// break the loop or come out of loop
break;
}
}
}
}