Advanced Selenium Interview Questions and Answers 2025

HOME

Number of Tests * Average Test Time / Number of Nodes = Total Execution Time
 
15      *       45s        /        1        =      11m 15s   // Without Grid
15      *       45s        /        5        =      2m 15s    // Grid with 5 Nodes
15      *       45s        /        15       =      45s       // Grid with 15 Nodes

To know more about the steps to configure Selenium4, please refer to Selenium 4 Grid – Parallel Testing.

(//parentElement/*)[n]

import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
 
public class ProxyDemo {
 
    public static void main(String[] args) {
 
        // Set the proxy server details
        String proxyAddress = "localhost";
        int proxyPort = 8080;
 
        // Create a Proxy object and set the HTTP proxy details
        Proxy proxy = new Proxy();
        proxy.setHttpProxy(proxyAddress + ":" + proxyPort);
 
        // Configure Chrome options with the Proxy object
        ChromeOptions options = new ChromeOptions();
        options.setProxy(proxy);
        options.addArguments("start-maximized");
 
        // Instantiate ChromeDriver with the configured options
        WebDriver driver = new ChromeDriver(options);
 
 
        // Perform your browsing actions using the driver
        driver.get("https://www.google.com");
        System.out.println("Page Title :" + driver.getTitle());
 
        // Close the browser session
        driver.quit();
    }
}

WebDriver driver = new ChromeDriver(); // For Chrome

WebDriver driver = new FirefoxDriver(); // For Firefox

WebDriver driver = new EdgeDriver(); // For Edge

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