isDisplayed, isSelected, isEnabled in Selenium

HOME

This tutorial describes how to check the state of a WebElement in Selenium.

In this tutorial, we will learn the isDisplayed, isEnabled, isSelected method in Selenium, and how to check the state of a WebElement. There are many methods that are used to determine the visibility scope for the web elements – isSelected(), isEnabled(), and isDispalyed().

Many a time, a test fails when we click on an element or enter text in a field. This is because the element is displayed or exists in DOM, but it does not exist on the web page.

WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels, etc.

  • isDisplayed()
  • isSelected()
  • isEnabled()

1) Boolean isSelected(): This method determines if an element is selected or not. It returns true if the element is selected and false if it is not. It is widely used on checkboxes, radio buttons, and options in a select.

2) Boolean isDisplayed(): This method determines if an element is displayed or not. It returns true if the element is displayed and false if it is not. The advantage of this method is that it avoids parsing an element’s style attribute.

3) Boolean isEnabled(): This method determines if an element is enabled or not. It returns true if the element is enabled (All elements apart from disabled input elements) and false if otherwise.

Steps to follow to understand when an element isEnabled and isDisplayed.

  1. Launch the web browser and open the application under test – https://duckduckgo.com/
  2. Verify the web page title
  3. Verify if the “Search Box” is displayed
  4. Verify that the “Search Box” is enabled
  5. If Search Box is enabled, then search for text – Selenium
  6. Close the browser

The complete program is shown below:

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;

import java.util.concurrent.TimeUnit;

public class VerifyConditionsDemo {

    public static void main(String[] args) {

        // Initiate Firefox browser
        FirefoxOptions options = new FirefoxOptions();
        WebDriver driver = new FirefoxDriver(options);

        // Maximize the browser
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

        // launch the firefox browser and open the application url
        driver.get("https://duckduckgo.com/");

        // compare the expected title of the page with the actual title of the page and
        String expectedTitle = "DuckDuckGo — Privacy, simplified.";
        String actualTitle = driver.getTitle();
        if (expectedTitle.equals(actualTitle)) {
            System.out.println("Verification Pass- The correct title is displayed on the web page.");
        } else {
            System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
        }

        // Verify that the “Search" Box is displayed
        WebElement searchBox = driver.findElement(By.className("searchbox_input__bEGm3"));
        if (searchBox.isDisplayed()) {
            System.out.println("Search Box is visible. Return: " + searchBox.isDisplayed());
        } else {
            System.out.println("Search Box is not visible. Return: " + searchBox.isDisplayed());
        }

        // Verify that the “Search” Box is enabled
        if (searchBox.isEnabled()) {
            System.out.println("Search Box is enabled. Return: " + searchBox.isEnabled());
            searchBox.sendKeys("Selenium");
        } else {
            System.out.println("Search Box is not enabled. Return: " + searchBox.isEnabled());
        }

        System.out.println("Successful Execution of Test.");

        // close the web browser
        driver.close();

    }
}

The output of the above program is

isSelected

Steps to follow to understand when an element is Selected or not

  1. Launch the web browser and open the application under test – https://demoqa.com/radio-button
  2. Print all the options for the Radio Button
  3. Verify if the first Radio Button (Yes) is selected or not
  4. If the first radio button is not selected, then select Radio Button 1, else select button 2.
  5. Print the value of the selected Radio Button
  6. Close the browser

Below is the image of the options for the Radio Button.

The complete program is shown below:

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class isSelectedDemo {

        public static void main(String[] args) {


            // Initiate Firefox browser
            FirefoxOptions firefoxOptions = new FirefoxOptions();
            WebDriver driver = new FirefoxDriver(firefoxOptions);

            // Maximize the browser
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

            driver.get("https://demoqa.com/radio-button");

            List<WebElement> Radio_Options = driver.findElements(By.cssSelector(".custom-radio"));
            for(WebElement options: Radio_Options)
                System.out.println("Options :"+ options.getText());

            // Create a boolean variable which will hold the value (True/False)
            boolean radio_value = false;

            // This statement will return True, in case of first Radio button is already selected
            radio_value = Radio_Options.get(0).isSelected();
            System.out.println("First Option is already selected :"+radio_value);

            // If button 1 is not selected, then select otherwise select button 2
            if (radio_value == false) {
                Radio_Options.get(0).click();
                System.out.println("Button Selected is :" + Radio_Options.get(0).getText());
            } else {
                Radio_Options.get(1).click();
                System.out.println("Button Selected is :" + Radio_Options.get(1).getText());
            }

            // close the web browser
            driver.close();
        }
    }

The output of the above program is

That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

How to Select value from Drop down list or perform Multiple Selection Operations in Selenium WebDriver

HOME


In the previous tutorial, it is explained how to automate Checkbox in Selenium. In this tutorial, we will learn how to handle Drop Down & Multiple Select Operations. DropDownMultiple Select Operations work together and almost the same way. The only difference between these two deselecting statements & multiple selections is not allowed on DropDown.

To identify DropDown or multi-select list on a web page, we can use any one of the options like idnamexpathcss, etc. 

To perform any operation on DropDown, we need to do 2 things:-

1) Selenium WebDrivers provides a class called “Select “class that is used to automate dropdown, and it is imported from the package:

org.openqa.selenium.support.ui.Select

2) Create a new Select object of class Select.

Select oSelect = new Select());

We can access all the methods residing inside the SELECT class by typing oSelect + dot.

Different Select Commands

Before we discuss various select commands, we should know how the HTML code of DropDown actually looks

1) selectByVisibleText 

selectByVisibleText(String arg0): void – Choose the option given under any dropdowns and multiple selection boxes with selectByVisibleText method. It takes a parameter of String that is one of the Value of Select element and it returns nothing.

To select the text One

select.selectByVisibleText("One");

2)  selectByIndex 

selectByIndex(int arg0): void – It is almost the same as selectByVisibleText but the only difference here is that we provide the index number of the option here rather than the option text. It takes a parameter of int which is the index value of the Select element and it returns nothing.

To select the value 3 using index

 select.selectByIndex(3);

3) selectByValue

selectByValue(String arg0): void –  It selects the option of the value. It takes a parameter of String that is of the value of the Select element and it returns nothing.

To select the value of two

 Select mselect = new Select(driver.findElement(By.id("redirect")));
 mselect.selectByValue("two");

Let us explain this with the help of an example.

1) Launch a new Browser and open https://www.selenium.dev/selenium/web/formPage.html
2) Print the list of options in the dropdown.
3) Select option ‘One’ (Use selectByVisibleText)
4) Select option ‘3’ (Use selectByIndex)
5) Select option ‘two’ (Use selectByValue)
6) Close the browser

The complete program looks like as shown below:

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.support.ui.Select;

import java.time.Duration;
import java.util.List;

public class DropDown_Demo {

    public static void main(String[] args)  {

        // Initiate Firefox browser
        FirefoxOptions firefoxOptions = new FirefoxOptions();
        WebDriver driver = new FirefoxDriver(firefoxOptions);

        // Implicit Wait
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));

        // Pass application url
        driver.get("https://www.selenium.dev/selenium/web/formPage.html");

        //Get the list of options from dropdown
        Select select = new Select(driver.findElement(By.name("select-default")));
        List<WebElement> listElements = select.getOptions();
        System.out.println("List of options in dropdown:" );
        for(WebElement options: listElements)
            System.out.println(options.getText());

        // Select option 'Two' (Use selectByVisibleText)
        System.out.println("Select the Option by Text - One");
        select.selectByVisibleText("One");

        // Select option '3' (Use selectByIndex)
        System.out.println("Select the Option by Index 3 - Still learning how to count, apparently");
        select.selectByIndex(3);

        // Select option 'two' (Use selectByValue)
        System.out.println("Select the Option by selectByValue - two");
        Select mselect = new Select(driver.findElement(By.id("redirect")));
        mselect.selectByValue("two");

        // close the browser
        driver.close();
    }

}

The output of the above program is

Different DeSelect Methods

The way we select different values of DropDown and Multi Select, we can deselect the options similarly.

1) deselectAll

deselectAll( ): void – Clear all selected entries. This is only valid when the SELECT supports multiple selections.

Syntax:

oSelect.deselectAll;

2) deselectByIndex

deselectByIndex(int arg0): void –Deselect the option at the given index.

Syntax:

oSelect.deselectByIndex;

3) deselectByValue

deselectByValue(String arg0): void –Deselect all options that have a value matching the argument.

Syntax:

 oSelect.deselectByValue;

4) deselectByVisibleText

deselectByVisibleText(String arg0): void – Deselect all options that display text matching the argument.

Syntax:

oSelect.deselectByVisibleText

Below is an example of how to operate on multi-selection options.

1) Launch a new Browser and open https://www.selenium.dev/selenium/web/formPage.html
2) Print the list of options in the dropdown.
3) Select options ‘eggs’ and ‘sausages’.
4) Print and select all the options for the selected Multiple selection list.
5) Deselect option eggs.
6) Deselect all options
7) Close the browser

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.support.ui.Select;

import java.time.Duration;
import java.util.List;

public class MultiSelect_Demo {
    
    public static void main(String[] args) {

        // Initiate Firefox browser
        FirefoxOptions firefoxOptions = new FirefoxOptions();
        WebDriver driver = new FirefoxDriver(firefoxOptions);

        // Implicit Wait
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));

        // Pass application url
        driver.get("https://www.selenium.dev/selenium/web/formPage.html");

        //Get the list of options from dropdown
        Select select = new Select(driver.findElement(By.name("multi")));
        List<WebElement> listElements = select.getOptions();
        System.out.println("List of options in dropdown:");
        for (WebElement options : listElements)
            System.out.println(options.getText());

        // Select option 'Ham' (Use selectByVisibleText)
        System.out.println("Select the Option by Text - Eggs");
        select.selectByVisibleText("Eggs");

        // Select option '2' (Use selectByIndex)
        System.out.println("Select the Option by Index 2 - Sausages");
        select.selectByIndex(2);

        System.out.println("*************************************");
        //Get the list of selected options
        System.out.println("The selected values in the dropdown options are -");
        List<WebElement> selectedOptions = select.getAllSelectedOptions();

        for(WebElement selectedOption: selectedOptions)
            System.out.println(selectedOption.getText());

        // Deselect the value "eggs" by Value
        System.out.println("*************************************");
        System.out.println("DeSelect option eggs by Value");
        select.deselectByValue("eggs");

        System.out.println("*************************************");
        System.out.println("The latest selected values in the dropdown options are -");
        List<WebElement> reselectedOptions = select.getAllSelectedOptions();

        for(WebElement selectedOption: reselectedOptions)
            System.out.println(selectedOption.getText());

        select.deselectAll();

        driver.quit();
    }
}

The output of the above program is

That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

WebDriver Navigation Commands – Navigate, Forward, Back, Refresh in Selenium WebDriver

HOME

1) Navigate

This command loads a new web page in the current window as mentioned in the argument. This command accepts a string parameter and returns nothing.

This command performs the same action as the get() command.

Syntax:

to(String arg0):void

Command:

driver.navigate().to(URL);

2) Forward

This command acts as the same as clicking on the Forward button of any web browser. This command does not require any parameter, and void means return nothing. 

Syntax:

forward(): void 

Command:

driver.navigate().forward();

3) Back

This command acts the same as clicking on the Back button of any web browser. This command does not require any parameter, and void means return nothing. 

Syntax:

back(): void

Command:

driver.navigate().back();

4) Refresh

This command refreshes the current page. This command does not require any parameter, and void means return nothing. 

Syntax:

 refresh(): void 

Command:

driver.navigate().refresh();

How to use Navigation Commands in Selenium WebDriver:

  • Create an instance of ChromeDriver() to handle Navigation commands.
  • Wait until Page Load.
  • Navigate to URL – https://selenium.dev
  • Navigate to another URL.
  • Navigate to the back page.
  • Navigate to the forward page.
  • Refresh the current page.
  • Close the browser

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

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

		ChromeOptions options = new ChromeOptions();
		options.addArguments("--start-maximized");
		options.setImplicitWaitTimeout(Duration.ofSeconds(10));
		
		WebDriver driver = new ChromeDriver(options);
        driver.navigate().to("https://selenium.dev");
        
        //Get the Title of web page
        String PageTitle= driver.getTitle();
        System.out.println("Title of Page 1 is : " + PageTitle);    
        
        Thread.sleep(2000);
        System.out.println("Navigate to New Page 2");
        driver.findElement(By.xpath("//*[@id='main_navbar']/ul/li[4]/a/span")).click();

        Thread.sleep(2000); 
        System.out.println("Navigate back to Old Page 1");
        driver.navigate().back();
 
        Thread.sleep(2000);
        System.out.println("Navigate forward to New Page 2");    
        driver.navigate().forward();
    
        Thread.sleep(2000);
        System.out.println("Refresh the existing page");    
        driver.navigate().refresh();
        
        //quit the browser
        driver.quit();
	}

}

Selenium Interview Questions and Answers 2025

HOME

driver.findElement(By.id("email")) 


driver.findElement(By.xpath("/html/body/form/content"));

Double Slash “//” – Double slash is used to create an XPath with a relative path i.e. the XPath would be created to start selection from anywhere within the document. For example, the below example will select any element in the document which has an attribute named “id” with the specified value “email”.

driver.findElement(By.xpath("//*[@id = 'email']")

For more details, click here


4. How do we can launch the browser using WebDriver?

Firstly, we should instantiate a Chrome/Chromium session by doing the following

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
           
 ChromeOptions options = new ChromeOptions();
 WebDriver driver = new ChromeDriver(options);

The chromedriver is implemented as a WebDriver remote server that instructs the browser what to do by exposing Chrome’s internal automation proxy interface.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;

         FirefoxOptions firefoxOptions = new FirefoxOptions();
        WebDriver driver = new FirefoxDriver(firefoxOptions);

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

      EdgeOptions options = new EdgeOptions();
      WebDriver driver = new EdgeDriver(options);

For more details, click here 


5. What are the different types of Drivers available in WebDriver?

The different drivers available in WebDriver are

  • FirefoxDriver
  • InternetExplorerDriver
  • ChromeDriver
  • SafariDriver
  • OperaDriver
  • AndroidDriver
  • IPhoneDriver
  • HtmlUnitDriver

6. Explain the different exceptions in Selenium WebDriver

Exceptions in Selenium are similar to exceptions in other programming languages. The most common exceptions in Selenium are:


1. TimeoutException: This exception is thrown when a command performing an operation does not complete in the expected time.

2. NoSuchElementException: This exception is thrown when an element with given attributes is not found on the web page. Suppose webdriver is trying to click on XPath – “//*[@id=’yDmH0d’]/div/div[2]/div[2]/form/content” which doesn’t exist on that particular web page, then the below exception is displayed – org.openqa.selenium.NoSuchElementException.

3. ElementNotVisibleException: This exception is thrown when the element is present in DOM (Document Object Model), but not visible on the web page.

4. StaleElementException: This exception is thrown when the element is either deleted or no longer attached to the DOM. This exception occurs, when Selenium navigates to a different page, comes back to the same old page, and performs operations on the old page. Technically, it occurs when the element defined in the Selenium code is not found in the cache memory and the Selenium code is trying to locate it. 


7. What are the different types of waits available in WebDriver?

How do you achieve synchronization in WebDriver?

There are three types of wait in Selenium WebDriver

 1.   Implicit Wait – The implicit wait will tell to the web driver to wait for a certain amount of time before it throws a “NoSuchElementException“. The default setting is 0. Once we set the time, the web driver will wait for that time before throwing an exception. Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command across the entire test script.
We need to import java.util.concurrent.TimeUnit to use ImplicitWait.

    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));

2.    Explicit Wait – An explicit wait is a code you define to wait for a certain condition to occur before proceeding further in the code. The explicit wait will tell the web driver to wait for certain conditions like visibilityOfElementLocated and the maximum amount of time before throwing the NoSuchElementException exception. Unlike Implicit waits, explicit waits are applied for a particular instance only.

 Wait<WebDriver> wait = new WebDriverWait(driver, Duration.ofSeconds(2));
  wait.until(d -> revealed.isDisplayed());

3.  Fluent Wait – Fluent Wait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition.

Users may configure the wait to ignore specific types of exceptions whilst waiting, such as  NoSuchElementException when searching for an element on the page.

Fluent Wait commands are mainly used when the web elements which sometimes visible in a few seconds and sometimes take more time than usual. Mainly in Ajax applications. We could set the default pooling period based on the requirement.

Wait<WebDriver> wait =
        new FluentWait<>(driver)
            .withTimeout(Duration.ofSeconds(2))
            .pollingEvery(Duration.ofMillis(300))
            .ignoring(ElementNotInteractableException.class);

    wait.until(
        d -> {
          revealed.sendKeys("Displayed");
          return true;
        });

For more details, click here 


8. How to set the size of the Window in Selenium WebDriver?

First, fetch the size of the browser window in pixels by the below code Dimension

//Access each dimension individually
int width = driver.manage().window().getSize().getWidth();
int height = driver.manage().window().getSize().getHeight();

//Or store the dimensions and query them later
Dimension size = driver.manage().window().getSize();
int width1 = size.getWidth();
int height1 = size.getHeight();

Now, change the size of the window by using

driver.manage().window().setSize(new Dimension(1024, 768)); 

9. How to set the position of Window in Selenium?

First fetch the coordinates of the top left coordinate of the browser window by

// Store the dimensions and query them later
Point position = driver.manage().window().getPosition();
         int x1 = position.getX();
         int y1 = position.getY();

// Access each dimension individually
int x = driver.manage().window().getPosition().getX();
int y = driver.manage().window().getPosition().getY();

The window can be moved to the chosen position by

// Move the window to the top left of the primary monitor
driver.manage().window().setPosition(new Point(0, 0));

10. What is the difference between driver.findElement() and driver.findElements() commands?

FindElement – This method locates the first web element on the current web page matching the criteria mentioned as the parameter.  
If the web element is not found, it will throw an exception – NoSuchElementException. 

driver.findElement(By.xpath("Xpath location"));

FindElements – This method locates all the web elements on the current web page matching the criteria mentioned as parameters. 

If not found any WebElement on the current page as per the given element locator mechanism, it will return the empty list.     

findElements (By arg0):List<WebElement

For more details, click here 


11. How to type in a textbox using Selenium?

The user can use sendKeys(“String to be entered”) to enter the string in the textbox. The sendKeys type a key sequence in the DOM element even if a modifier key sequence is encountered.

Syntax - sendKeys(CharSequence… keysToSend ) : void
Command – driver.findElement(By.xpath("//*[@name = 'email']")).sendKeys("abc123@gmail.com") 

For more details, click here


12. How can we get a text of a web element?

The get command is used to retrieve the inner text of the specified web element. The command doesn’t require any parameter but returns a string value. It is also one of the extensively used commands for verification of messages, labels, errors, etc displayed on the web pages. 

String Text = driver.findElement(By.id(“Text”)).getText();

13. How to input text in the text box without calling the sendKeys()?

//Creating the JavascriptExecutor interface object by Type casting                                     JavascriptExecutor js = (JavascriptExecutor)driver;              

//Launching the Site        
driver.get("https://www.google.com/");                      
js.executeScript("document.getElementsByName('q')[0].value = 'Selenium Introduction';");

Actions actions = new Actions(driver);
actions.moveToElement(element).click().sendKeys("Selenium Introduction").build().perform();

For more details, click here


14. How to read a JavaScript variable in Selenium WebDriver? 

//To initialize the JS object
JavascriptExecutor JS = (JavascriptExecutor) webdriver;

//To get the site title
String title = (String)JS.executeScript("return document.title");
System.out.println("Title of the webpage : " + title);

For more details, click here


15. What is JavaScriptExecutor and in which cases JavaScriptExecutor will help in Selenium automation?

There are some conditions where we cannot handle problems with only WebDriver. Web controls don’t react well to selenium commands. In this kind of situation, we use Javascript. It is useful for custom synchronizations, hiding or showing web elements, changing values, testing flash/HTML5, and so on. 
To do these, we can use Selenium’s JavascriptExecutor interface which executes JavaScript through Selenium driver.

It providesexecutescript” & “executeAsyncScript methods, to run JavaScript in the context of the currently selected frame or window.

JavascriptExecutor js = (JavascriptExecutor) driver; 
js.executeScript(Script,Arguments);

Script – This is the JavaScript that needs to be executed.

Arguments – It is the arguments to the script. It’s optional
Let’s see some scenarios we could handle using this Interface:
1. To type Text in Selenium WebDriver without using sendKeys() method 2. To click a Button in Selenium WebDriver using JavaScript
3. To handle Checkbox
4. To generate an Alert Pop window in Selenium
5. To refresh the browser window using Javascript
6. To get inner text of the entire webpage in Selenium
7. To get the Title of our webpage
8. To get the domain
9. To get the URL of a webpage
10. To perform Scroll on an application using  Selenium


For more details, click here


16. How To Highlight Element Using Selenium WebDriver?

By using the JavascriptExecutor interface, we could highlight the specified element

//Create the JavascriptExecutor interface object by Type casting               
JavascriptExecutor js = (JavascriptExecutor)driver; 

//Higlight element - Total PageCount
WebElement TotalCount = driver.findElement(By.id("Stats1"));
js.executeScript("arguments[0].style.border='3px dotted blue'", TotalCount); 

For more details, click here


17. List some scenarios that we cannot automate using Selenium WebDriver?


18. How can you find if an element is displayed on the screen?

WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels, etc.

  • isDisplayed()
  • isSelected()
  • isEnabled()
isDisplayed():
boolean elePresent = driver.findElement(By.xpath("xpath")).isDisplayed();
isSelected():
boolean eleSelected= driver.findElement(By.xpath("xpath")).isSelected(); 
isEnabled():
boolean eleEnabled= driver.findElement(By.xpath("xpath")).isEnabled();

19. Explain how you can switch back from a frame?

To switch back from a frame use the method defaultContent().  

driver.switchTo().defaultContent(); 

20. What is the difference between getWindowhandles() and getwindowhandle() ?

getwindowhandles(): It is used to get the address of all the open browser and its return type is Set<String>

getwindowhandle(): It is used to get the address of the current browser where the control is and return type is string.

For more details, click here


21. How to select the value in a dropdown?

To perform any operation on DropDown, we need to do 2 things:-

1) Import package org.openqa.selenium.support.ui.Select 
2) Create a new Select object of the class Select

Select oSelect = new Select());
Different Select Commands
Select yselect = new Select(driver.findElement(By.id("year")));
yselect.selectByValue("1988");
 Select mselect = new Select(driver.findElement(By.id("month")));
 mselect.selectByVisibleText("Apr");
Select bselect = new Select(driver.findElement(By.name("birthday_day")));
bselect.selectByIndex(8);

For more details, click here


22. How to switch to a new window (new tab) that opens up after you click on a link?

If you click on a link in a web page and it opens a new window, but WebDriver will not know which window the Operating system consider active. To change the WebDriver’s focus/ reference to the new window we need to use the switchTo() command. driver.switchTo().window();

Here, ‘windowName’ is the name of the window you want to switch your reference to.

In case you do not know the name of the window, then you can use the driver.getWindowHandle() command to get the name of all the windows that were initiated by the WebDriver. Note that it will not return the window names of browser windows which are not initiated by your WebDriver.

Once you have the name of the window, then you can use an enhanced for loop to switch to that window. Look at the piece of code below.

String handle= driver.getWindowHandle();
for (String handle : driver.getWindowHandles()) 
{
driver.switchTo().window(handle); 
}

//Store the ID of the original window
String originalWindow = driver.getWindowHandle();

//Check we don't have other windows open already
 assert driver.getWindowHandles().size() == 1;

 //Click the link which opens in a new window
 driver.findElement(By.linkText("new window")).click();

 //Wait for the new window or tab
 wait.until(numberOfWindowsToBe(2));
  
//Loop through until we find a new window handle
for (String windowHandle : driver.getWindowHandles()) {
    if(!originalWindow.contentEquals(windowHandle)) {
        driver.switchTo().window(windowHandle);
        break; 
    } 
}
  
//Wait for the new tab to finish loading content
wait.until(titleIs("Selenium documentation"));  

For more details, click here


23. How to handle browser (chrome) notifications in Selenium?

In Chrome, we can use ChromeOptions as shown below.

ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
WebDriver player = new ChromeDriver(options);

24. How to delete Browser Cookies with Selenium Web Driver?

driver.Manage().Cookies.DeleteAllCookies();
driver.manage().deleteCookieNamed("cookie_name");
// Get the cookie
Cookie cookie = driver.manage().getCookieNamed("cookie_name");

// Delete the specific cookie
driver.manage().deleteCookie(cookie);

25. What are the different types of navigation commands?

  • driver.navigate().forward(); – to navigate to the next web page with reference to the browser’s history.
  • driver.navigate().back(); – takes back to the previous webpage with reference to the browser’s history.
  • driver.navigate().refresh(); – to refresh the current web page thereby reloading all the web elements.
  • driver.navigate().to(“url”); – to launch a new web browser window and navigate to the specified URL.

For more details, click here


26. How can we handle Web-based Pop-ups or Alerts in Selenium?

To handle Web-based alerts or popups, we need to do switch to the alert window and call Selenium WebDriver Alert API methods.

  • dismiss(): To click on Cancel button.
  • accept(): To Click on OK button.
  • getText(): To get the text which is present on the Alert.
  • sendKeys(): To enter the text into the alert box.

For more details, click here


27. What are the ways to refresh a browser using Selenium WebDriver?

1. Using driver.navigate().refresh() command.
2. Using driver.get(“URL”) on the current URL or using driver.getCurrentUrl()
3. Using driver.navigate().to(“URL”) on the current URL or driver.navigate().to(driver.getCurrentUrl());
4. Using sendKeys(Keys.F5) on any textbox on the webpage.        



28. What are the different mouse actions that can be performed?

The different mouse events supported in selenium are
1. click(WebElement element)
2. doubleClick(WebElement element)
3. contextClick(WebElement element)
4. mouseDown(WebElement element)
5. mouseUp(WebElement element)
6. mouseMove(WebElement element)
7. mouseMove(WebElement element, long xOffset, long yOffset)

For more details, click here


29. Write the code to double-click an element in selenium?

To double-click an element in Selenium, you can use the Actions class, which provides the doubleClick() method. The code to double-click an element in selenium is mentioned below

driver.get("https://www.selenium.dev/selenium/web/mouse_interaction.html");

WebElement clickable = driver.findElement(By.id("clickable"));
new Actions(driver)
.doubleClick(clickable)
.perform();

30. Write the code to right-click an element in selenium?

To right-click an element in Selenium, you can use the Actions class, which provides the contextClick() method for performing a right-click action. Below is an example:

 driver.get("https://www.selenium.dev/selenium/web/mouse_interaction.html");

WebElement clickable = driver.findElement(By.id("clickable"));
new Actions(driver)
.contextClick(clickable)
.perform();

31. How to mouse hover an element in selenium?

// Launch the URL
driver.get("https://www.selenium.dev/selenium/web/mouse_interaction.html");

WebElement hoverable = driver.findElement(By.id("hover"));
	     
new Actions(driver)
.moveToElement(hoverable)
.perform();

Using the Action class, drag and drop can be performed in selenium.

// Launch the URL
driver.get("https://www.selenium.dev/selenium/web/mouse_interaction.html");

WebElement hoverable = driver.findElement(By.id("hover"));
	     
new Actions(driver)
.moveToElement(hoverable)
.perform();

    Or
driver.get("https://www.selenium.dev/selenium/web/mouse_interaction.html");
 
WebElement draggable = driver.findElement(By.id("draggable"));
WebElement droppable = driver.findElement(By.id("droppable"));
new Actions(driver)
.dragAndDrop(draggable, droppable)
.perform();

33. How can we capture screenshots in selenium?

Using the getScreenshotAs method of the TakesScreenshot interface, we can take the screenshots in selenium.

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\testScreenShot.jpg"));


Set<Cookie> cookies = driver.manage().getCookies();
driver.manage().getCookieNamed(arg0);
Cookie cookie = new Cookie("cookieName", "cookieValue");
driver.manage().addCookie(cookie);
driver.manage().deleteCookieNamed("cookieName");
driver.manage().deleteAllCookies();


Advanced Selenium Interview Questions and Answers

Difference between getText() and getAttribute() method in Selenium WebDriver

In this tutorial, we will discuss GetText() method as well as the getAttribute() method in Selenium WebDriver. These methods are used extensively in automating a web application. Before going through these methods, we should know what HTML attributes are.

What are HTML attributes?

Attributes are the additional information provided by developers in HTML tags. Attributes are normally defined using “name-pair” values. Let us see, here div is the tag, and corresponding attribute with the property name is id, and the property value is nav-xshop.
<div id= “nav-xshop”>


What is getAttribute() method?

The getAttribute() method is declared in the WebElement interface, and it returns the value of the web element’s attribute as a string. It fetches the value of an attribute, in HTML code whatever is present in the left side of ‘=’ is an attribute, and the value on the right side is an attribute value.

  • getAttibute() returns ‘null’ if there is no such attributes
  • getAttribute() method will return either “true” or null for attributes whose value is Boolean.

Where to use getAttribute() method?

Consider a scenario of movie ticket booking. The colour of booked and available seats in the movie theatre is different. So the same seat will have the supposed white colour for the available seat and blue for the booked seat. So, the colour attribute of the seat changes from white to blue for the same seat, which can be identified by the getAttribute() method. The snippet below shows the HTML code of the search box of the Amazon Home page

Below is an example of how the getAttribute() method can be used.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class GetAttributeDemo {
      public static void main(String[] args) {
 
            System.setProperty("webdriver.chrome.driver",
                                                "C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
 
             WebDriver driver = new ChromeDriver();
 
             driver.get("https://www.amazon.com/");
             driver.manage().window().maximize();
 
             WebElement AmazonSearchBox = driver.findElement(By.name("field-keywords"));
             System.out.println("Name of the Email Textbox is:- " + AmazonSearchBox.getAttribute("name"));
 
             System.out.println("Class of the Email Textbox is:- " + AmazonSearchBox.getAttribute("class"));
 
             System.out.println("Value of the Email Textbox is:- " + AmazonSearchBox.getAttribute("tabindex"));
 
             System.out.println("Type of the Email Textbox is:- " + AmazonSearchBox.getAttribute("type"));
 
             System.out.println("Id of the Email Textbox is:- " + AmazonSearchBox.getAttribute("id"));
 
             // getAttibute() returns 'null' if there no such attribute
 
             System.out.println("Value of nonExistingAttribute is:- " + AmazonSearchBox.getAttribute("test"));
 
            driver.close();
       }
 
}

Output
Name of the Email Textbox is:- field-keywords
Class of the Email Textbox is:- nav-input
Value of the Email Textbox is:- 19
Type of the Email Textbox is:- text
Id of the Email Textbox is:- twotabsearchtextbox
Value of nonExistingAttribute is:- null

What is getText() method?

getText() is a method that gets us the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing white space.

Inner text is the text between the opening tags and closing tags.

This is an example of getText().

In the above example, the text  “This is the example of getText” between opening and closing tags of h1 are called inner text.

The snippet below shows the HTML code of the search box of the Amazon Home page

Below is an example of how the getText() method can be used.

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class GetTextDemo {
 
      public static void main(String[] args) {
           System.setProperty("webdriver.chrome.driver",
                                                "C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
 
            WebDriver driver = new ChromeDriver();
 
            driver.get("https://www.facebook.com/");
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 
            String FacebookText = driver
                                    .findElement(By.xpath("//*[@id='content']/div/div/div/div/div[2]/div/div[1]/div[1]/span")).getText();
            System.out.println("Text on Facebook Site:- " + FacebookText);
         driver.close();
      }
 
}

Output
Text on Facebook Site:- Create an account

Execute JavaScript with executeAsyncScript() Method in Selenium

HOME

In the previous blog, we have discussed about executeScript() method in JavaScript. JavascriptExecutor interface comprises of executeAsyncScript() method that is called an additional final argument “arguments[arguments.lenght-1];”which is a callback function to signal that async execution has finished. We have to call from JavaScript, to tell Webdriver, that our Asynchronous execution has finished. If we do not do that, then executeAsyncScpriptwill timeout and throw a timeout exception.

Before executing AsyncScript method, we have to make sure to set the script timeout. Its default is 0. If we do not set a script timeout, our executeAsyncScript will immediately timeout and it won’t work.

Below is the program which shows how to use executeAsyncScript() method

  1. First  will get the start time before waiting 5 seconds by using executeAsyncScript() method.
  2. Then, will use executeAsyncScript() to wait 5 seconds.
  3. Then, will get the current time
  4. Will subtract (current time – start time) = passed time and print the value
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public classExecuteAsycSleepBrowserDemo {
        public static void main(String[] args) { 
    

System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver = newChromeDriver();
                                        
        //Create the JavascriptExecutor interface object by Type casting              
        JavascriptExecutor js = (JavascriptExecutor)driver;              
        driver.get("https://www.google.com/");                              
        driver.manage().window().maximize();
                        
        //Declare and set start time
        long startTime = System.currentTimeMillis();
                 
        //Call executeAsyncScript() method                       js.executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 5000);"); 
                 
        //Get the difference (currentTime - startTime) it should be greater than 5000
        System.out.println("Passed time: " + (System.currentTimeMillis() - startTime));
                        
          if ( (System.currentTimeMillis() - startTime) > 5000)
             {
                 System.out.println("Time difference must be greater than 5000 milliseconds");
             }
          driver.quit();      
      }

Output
Passed time: 5040
Time difference must be greater than 5000 milliseconds

Execute JavaScript with executeScript() Method in Selenium

HOME

In the previous tutorial, we have discussed about JavaScript. There are some conditions where we cannot handle some problems with WebDriver only, web controls don’t react well against selenium commands. In this kind of situations, we use Javascript. JavaScriptExecutor comes separately and also comes under the WebDriver but both do the same thing. Within the WebDriver, it is named as ExecuteScript.

JavaScriptExecutor is an interface that provides a mechanism to execute Javascript through selenium driver. It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

ExecuteScript Method – This method executes JavaScript in the context of the currently selected frame or window in Selenium. The script used in this method runs in the body of an anonymous function (a function without a name). We can also pass complicated arguments to it. 

Execute the below selenium script. In this example,

  • Launch the site
  • Fetch the domain name of the site.
  • Fetch the URL of the site
  • Fetch the title name of the sit
  • Then navigate to a different page – google.com
  • Display Alert popup                                                                        
package SeleniumTutorial;
import org.openqa.selenium.JavascriptExecutor;
 
import org.openqa.selenium.WebDriver;
 
import org.openqa.selenium.chrome.ChromeDriver;
 
public classJavaScript_Demo {
        public static voidmain(String[] args) {
                        System.setProperty("webdriver.chrome.driver","C:\\Users\\SingVi04\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
 
        WebDriver driver= new ChromeDriver();
                                        
        //Create the JavascriptExecutor interface object by Type casting                
        JavascriptExecutor js = (JavascriptExecutor)driver;             
 
        driver.get("https://configureselenium.blogspot.com/");
 
        driver.manage().window().maximize();
  
 
       //Fetching the Domain Name of the site. Tostring() change object to name.                
        String DomainName = js.executeScript("return document.domain;").toString();                 
        System.out.println("Domain name of the site = "+DomainName);                                        
                        
        //Fetching the URL of the site. Tostring() change object to name          
        String url = js.executeScript("return document.URL;").toString();                
        System.out.println("URL of the site = "+url);                                      
                        
        //Method document.title fetch the Title name of the site. Tostring() change object to name          
       String TitleName = js.executeScript("return document.title;").toString();                        
       System.out.println("Title of the page = "+TitleName);                                  
                
        //Navigate to new Page i.e to generate access page. (launch new url)             
        js.executeScript("window.location = 'https://www.google.com/'");
        String NewTitleName = js.executeScript("return document.title;").toString();                      
        System.out.println("Title of the new page = "+NewTitleName);    
 
        //Alert
        js.executeScript("alert('Hello Everyone!');");
        driver.switchTo().alert().accept();
      
        driver.quit();
    }           
 }

JavaScript and JavaScriptExecutor in Selenium

 
 
What is JavaScript?
 

JavaScript is the preferred language inside the browser to interact with HTML dom. This means that a Browser has JavaScript implementation in it and understands the JavaScript commands.
WebDriver gives you a method called Driver.executeScript which executes the JavaScript in context of the loaded browser page. There are some conditions where we cannot handle some problems with WebDriver only, web controls do not react well against selenium commands. In this kind of situations, we use Javascript. It is useful for custom synchronizations, hide or show the web elements, change values, test flash/HTML5 and so on. In order to do these, we can use Selenium’s JavascriptExecutor interface that executes JavaScript through Selenium driver.

What is JavaScriptExecutor?

JavaScriptExecutor comes separately and comes under the WebDriver but both do the same thing. Within the WebDriver, it is name as ExecuteScript. JavaScriptExecutor is an interface that provides a mechanism to execute Javascript through selenium driver. It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

ExecuteScript Method

This method executes JavaScript in the context of the currently selected frame or window in Selenium. The script used in this method runs in the body of an anonymous function (a function without a name). We can also pass complicated arguments to it.

The script can return values. Data types returned are 

  • Boolean 
  • Long 
  • String 
  • List 
  • WebElement 
JavascriptExecutor js = (JavascriptExecutor) driver;  
js.executeScript(Script,Arguments);

Script – This JavaScript needs to execute.

Arguments – It is the arguments to the script. It is optional

Below is an example, which shows how executeScript method can be use. In this example, 

  1. Launch the site
  2. Scroll down by 600 pixel
  3. Refresh the page
  4. Highlight a particular element
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class JavaSE_Demo {
        public static void main(String[] args){        

System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver= new ChromeDriver();                         
 
        //Create the JavascriptExecutor interface object by Type casting              
         JavascriptExecutor js = (JavascriptExecutor)driver;                   
         driver.get("https://configureselenium.blogspot.com/");     
         driver.manage().window().maximize();               

         //Vertical scroll down by 600  pixels             
          js.executeScript("window.scrollBy(0,600)");                           
 
         //Refresh the page
          js.executeScript("history.go(0);");
                       
          //Higlight element - Total PageCount
          WebElement TotalCount= driver.findElement(By.id("Stats1"));
          js.executeScript("arguments[0].style.border='3px dotted blue'", TotalCount);                     
      }                          
}

How to enter text-using JavaScriptexecutor (Without Sendkeys)

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class JavaScript_EnterText {
        public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver = newChromeDriver();
                                        
         //Creating the JavascriptExecutor interface object by Type casting              
          JavascriptExecutor js = (JavascriptExecutor)driver;              
                                        
          //Launching the Site.         
          driver.get("https://www.google.com/");                      
                     
          //Maximize window            
          driver.manage().window().maximize();       
                        
          js.executeScript("document.getElementsByName('q')[0].value = 'Selenium Introduction';");
   } 
}   

How to automate Radio Button in Selenium WebDriver

HOME

Let’s go through the scenario below:-

1) Launch Chrome Browser
2) Maximize the current window
3) Implicitly wait for 5 sec
4) Open browser – https://demo.automationtesting.in/Register.html
5) Find the locator of all Radio Buttons
6) Find the number of Radio Buttons available
7) Print the name of the first option of the radio button
8) Select the first option of the radio button
9) Print the name of the second option of the radio button
10) Select the second option of the radio button
11) Close the browser

    ChromeOptions options = new ChromeOptions();
    WebDriver driver = new ChromeDriver(options);
    
    driver.manage().window().maximize();
    
    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
    driver.get("https://demo.automationtesting.in/Register.html");
    
    List<WebElement> Radio_Options = driver.findElements(By.xpath("//*[@name='radiooptions']"));
    
    int radioSize = Radio_Options.size();
    System.out.println("No Of Radio Button Options :" + radioSize);
    
    for (int i = 0; i < radioSize; i++) {
        System.out.println("Name of Radio Button :"+ Radio_Options.get(i).getAttribute("Value"));
        Radio_Options.get(i).click();
        System.out.println("Radio Button Option "+ (i+1) +" is selected");
    }
    
    driver.quit();
    

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    
    import java.time.Duration;
    import java.util.List;
    
    public class RadioButton_Demo {
    
        public static void main(String[] args) throws InterruptedException {
    
            // Initiate Chrome browser
            ChromeOptions options = new ChromeOptions();
            WebDriver driver = new ChromeDriver(options);
    
            // Maximize the browser
            driver.manage().window().maximize();
    
            // Put an Implicit wait and launch URL
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
            driver.get("https://demo.automationtesting.in/Register.html");
    
            // Find locator of all Radio Buttons
            List<WebElement> Radio_Options = driver.findElements(By.xpath("//*[@name='radiooptions']"));
    
            // Find no of Radio Buttons available and print their values
            int radioSize = Radio_Options.size();
            System.out.println("No Of Radio Button Options :" + radioSize);
    
            Thread.sleep(5000);
    
            for (int i= 0; i< radioSize; i++) {
                System.out.println("Name of Radio Button :"+ Radio_Options.get(i).getAttribute("Value"));
                Radio_Options.get(i).click();
                System.out.println("Radio Button Option "+ (i+1) +" is selected");
            }
            driver.quit()  ;
        }
    }
    

    How to automate BootStrap DropDown using Selenium WebDriver

     
    In the previous post, we have already seen How to Handle Dropdowns in Selenium WebDriver . In this post, we will see how to handle Bootstrap Dropdown using Selenium WebDriver.
     
    What is Bootstrap?
     
    • Bootstrap is a free front-end framework for faster and easier web development
    • Bootstrap includes HTML and CSS based design templates for typography, forms, buttons, tables, navigation, modals, image carousels and many other, as well as optional JavaScript plugins
    • Bootstrap also gives you the ability to easily create responsive designs
    • Bootstrap is compatible with all modern browsers (Chrome, Firefox, Internet Explorer, Edge, Safari, and Opera)

    What is Responsive Web Design?

    Responsive web design is about creating web sites, which automatically adjust themselves to look good on all devices, from small phones to large desktops.
    Bootstrap dropdowns and interactive dropdowns that are dynamically position and formed using list of ul and li html tags. To know more about Bootstrap, please click here

    How to get all the options of a Bootstrap dropdown


    Below is an example which will explain how to get all the options of a Bootstrap dropdown.

    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.chrome.ChromeDriver;
    public class BootStrapDemo {
            public static void main(String[] args) {
     System.setProperty("webdriver.chrome.driver","C:\\Users\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
    
              WebDriver driver= new ChromeDriver();
              driver.manage().window().maximize();
              driver.get("https://www.seleniumeasy.com/test/");
              driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    
                    // Clicking on Bootstrap Dropdown
                   driver.findElement(By.xpath("//*[@id='navbar-brand-centered']/ul[1]/li[1]/a")).click(); 
    
                    // Get the all WebElements inside the dropdown in List  
                   List dropdown_list =  driver.findElements(By.xpath("//ul[contains(@class,'dropdown-menu')]//li//a"));
    
                  // Printing the amount of WebElements inside the list
                   System.out.println("The Options in the Dropdown are: " + dropdown_list.size());
    
                  // Condition to get the WebElement for list
                  for(int i=0; i<dropdown_list.size(); i++)
                  {
                       // Printing All the options from the dropdown
                       System.out.println(dropdown_list.get(i).getText());
                }                                                                                       
          }
    }
    
    Output
    The Options in the Dropdown are: 29
    Simple Form Demo
    Checkbox Demo
    Radio Buttons Demo
    Select Dropdown List
    Input Form Submit
    Ajax Form Submit
    JQuery Select dropdown
    
    

    Here,

    1) Open a web page – https://www.seleniumeasy.com/test/
    2) Click on BootStrap DropDown – Input Forms by using (“//*[@id=’navbar-brand-centered’]/ul[1]/li[1]/a”
    3) Get the all WebElements inside the dropdown in List  by using
    (“//ul[contains(@class,’dropdown-menu’)]//li//a”)
    4) Print all the options of DropDown using dropdown_list.get(i).getText()

    How to select a particular option from Bootstrap dropdown

    In the below example, there is a Bootstrap dropdown. I want to
    Check if an element – Checkbox Demo is present in the dropdown or not.
    If Yes, click on that option.

    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.chrome.ChromeDriver;
     
    public class BootStrapDemo {
            public static void main(String[] args) {
    
    System.setProperty("webdriver.chrome.driver","C:\\Users\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
    
              WebDriver driver= new ChromeDriver();
              driver.manage().window().maximize();
              driver.get("https://www.seleniumeasy.com/test/");
              driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
     
                    // Clicking on Bootstrap Dropdown
                   driver.findElement(By.xpath("//*[@id='navbar-brand-centered']/ul[1]/li[1]/a")).click(); 
     
                    // Get the all WebElements inside the dropdown in List  
                   List dropdown_list =  driver.findElements(By.xpath("//ul[contains(@class,'dropdown-menu')]//li//a"));
     
                  // Printing the amount of WebElements inside the list
                   System.out.println("The Options in the Dropdown are: " + dropdown_list.size());
     
                  // Condition to get the WebElement for list
                  for(int i=0; i<dropdown_list.size(); i++)
                  {
                       // Printing All the options from the dropdown
                       System.out.println(dropdown_list.get(i).getText());                 
    // Checking the condition whether option in text "Checkbox Demo" is coming
     
              if(dropdown_list.get(i).getText().contains("Checkbox Demo"))
                {
                     // Clicking if text "Checkbox Demo" is there
                     dropdown_list.get(i).click();
                  // Breaking the condition if the condition get satisfied
                     break;
              }
           }
       driver.quit();            
      }
    }
    
    OutPut
    The Options in the Dropdown are: 29
    Simple Form Demo
    Checkbox Demo
    

    This program can be re-written by using Enhanced for loop instead of For loop.

    getText() can be replaced by getAttribute(“innerHTML”)

    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.chrome.ChromeDriver;
     
    public class BootStrapDemo {
            public static void main(String[] args) {
     System.setProperty("webdriver.chrome.driver","C:\\Users\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
    
              WebDriver driver= new ChromeDriver();
              driver.manage().window().maximize();
              driver.get("https://www.seleniumeasy.com/test/");
              driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
     
                    // Clicking on Bootstrap Dropdown
                   driver.findElement(By.xpath("//*[@id='navbar-brand-centered']/ul[1]/li[1]/a")).click(); 
     
                    // Get the all WebElements inside the dropdown in List  
                   List dropdown_list =  driver.findElements(By.xpath("//ul[contains(@class,'dropdown-menu')]//li//a"));
     
                  // Printing the amount of WebElements inside the list
                   System.out.println("The Options in the Dropdown are: " + dropdown_list.size());
     
                  // Condition to get the WebElement using Enhanced For loop
     
                   for(WebElement element:dropdown_list)
     
                  {
                       // Printing All the options from the dropdown
                       System.out.println(element.getAttribute("innerHTML"));             
     
                      // Checking the condition whether option in text "Checkbox Demo" is coming
           if(element.getAttribute("innerHTML").contains("Checkbox Demo")) 
                {
                     // Clicking if text "Checkbox Demo" is there
                     element.click();
                  // Breaking the condition if the condition get satisfied
                     break;
              }
           }
       driver.quit();            
      }
    }