Selenium Interview Questions

In this guide, we present you the top Selenium Interview Questions and Answers in detail.

What is Selenium and why is it used?

Selenium is an open-source framework used for automating web browsers. It is primarily used for automating web applications for testing purposes, ensuring that they behave as expected across different browsers and platforms. Selenium supports multiple programming languages and browsers, making it a versatile tool for developers and QA engineers.

What are the different components of Selenium?

Selenium consists of several components, each serving a specific purpose:

  • Selenium IDE: A record and playback tool for creating simple test cases.
  • Selenium WebDriver: A programming interface for creating robust, browser-based regression automation suites and tests.
  • Selenium Grid: A tool for running tests on different machines and browsers simultaneously, enabling parallel execution.

Explain the difference between Selenium 3 and Selenium 4.

Selenium 4 introduces several improvements and new features over Selenium 3, including:

  • Relative Locators: Allow locating elements based on their position relative to other elements.
  • Improved Selenium Grid: Enhanced architecture for better scalability and support for Docker.
  • Better Browser Support: Enhanced support for modern browsers with improved WebDriver implementations.
  • Enhanced Documentation and Debugging: More comprehensive guides and better debugging tools.
  • Native Support for Chrome DevTools Protocol: Allows deeper interaction with Chrome for advanced testing scenarios.

What is WebDriver in Selenium?

WebDriver is a core component of Selenium that provides a programming interface to create and execute test scripts. It interacts directly with the browser, enabling automation of user actions like clicking, typing, and navigating. WebDriver supports multiple browsers and allows tests to be written in various programming languages, making it a flexible tool for browser automation.

How do you locate elements in Selenium?

In Selenium, elements can be located using various strategies provided by the WebDriver API. The most common locators include:

  • ID: Locate elements by their unique ID attribute.
  • Name: Locate elements by their name attribute.
  • Class Name: Locate elements by their class attribute.
  • Tag Name: Locate elements by their tag name.
  • Link Text: Locate anchor elements by their visible text.
  • Partial Link Text: Locate anchor elements by partial matching of their visible text.
  • CSS Selector: Locate elements using CSS selectors for more complex queries.
  • XPATH: Locate elements using XPath expressions for advanced navigation and selection.

What is the difference between Absolute and Relative XPATH?

Absolute XPATH starts from the root element and follows the entire path to the target element. It is more fragile as any change in the DOM can break the path. Relative XPATH starts from a specific element and navigates to the target element, making it shorter, more readable, and more resilient to changes in the DOM structure.

How do you handle dynamic elements in Selenium?

Handling dynamic elements in Selenium can be achieved using various strategies:

  • Dynamic Locators: Use relative XPATH or CSS selectors that can adapt to changes.
  • Waits: Implement explicit waits to handle elements that load asynchronously.
  • Regular Expressions in Locators: Utilize regular expressions within locators to match dynamic patterns.
  • JavaScript Execution: Use JavaScript to interact with elements when traditional locators fail.

What are implicit and explicit waits in Selenium?

Selenium provides two types of waits to handle synchronization issues:

  • Implicit Wait: Sets a default wait time for the WebDriver to poll the DOM for a certain duration when trying to find an element if it is not immediately available.
  • Explicit Wait: Allows you to wait for a specific condition to occur before proceeding, offering more granular control over synchronization.

How do you handle alerts in Selenium?

Handling alerts in Selenium involves using the Alert interface provided by WebDriver. You can switch to the alert, accept or dismiss it, and retrieve its text. For example:

// Switch to alert
    Alert alert = driver.switchTo().alert();
    
    // Get alert text
    String alertText = alert.getText();
    
    // Accept the alert
    alert.accept();
    
    // Dismiss the alert
    alert.dismiss();
    

What is Selenium Grid and how does it work?

Selenium Grid is a tool that allows you to run tests on different machines and browsers simultaneously, enabling parallel execution. It consists of a Hub and multiple Nodes. The Hub acts as a central point where tests are sent, and the Nodes are the machines where the tests are executed. This setup helps in reducing the overall test execution time and ensures cross-browser compatibility.

How do you handle frames and windows in Selenium?

Handling frames and windows in Selenium involves switching the WebDriver’s context to the desired frame or window. For frames, you can switch using the frame’s index, name, or WebElement. For windows, you can switch based on window handles. Example for frames:

// Switching to a frame by index
    driver.switchTo().frame(0);
    
    // Switching back to the default content
    driver.switchTo().defaultContent();
    
    // Switching to a window
    String mainWindow = driver.getWindowHandle();
    for(String handle : driver.getWindowHandles()) {
        if(!handle.equals(mainWindow)) {
            driver.switchTo().window(handle);
            break;
        }
    }
    

What is the Page Object Model (POM) in Selenium?

The Page Object Model (POM) is a design pattern in Selenium that creates an object repository for web UI elements. Each web page in the application is represented by a separate class, and the elements on the page are defined as variables within the class. POM enhances test maintenance and reduces code duplication by separating the test scripts from the page-specific code.

How do you perform data-driven testing in Selenium?

Data-driven testing in Selenium involves separating test data from test scripts, allowing the same test to run multiple times with different data sets. This can be achieved using external data sources like Excel, CSV, XML, or databases. Frameworks like TestNG or JUnit can be integrated with Selenium to parameterize tests and iterate through data sets.

What is the difference between driver.close() and driver.quit() in Selenium?

driver.close() closes the current browser window that the driver is controlling, whereas driver.quit() closes all browser windows opened by the WebDriver and ends the WebDriver session. quit() is useful for cleanup after all tests have been executed.

How do you handle dropdowns in Selenium?

Handling dropdowns in Selenium can be done using the Select class provided by Selenium WebDriver. It allows selecting options by visible text, value, or index. Example:

import org.openqa.selenium.support.ui.Select;
    
    WebElement dropdown = driver.findElement(By.id("dropdownId"));
    Select select = new Select(dropdown);
    
    // Select by visible text
    select.selectByVisibleText("Option 1");
    
    // Select by value
    select.selectByValue("option2");
    
    // Select by index
    select.selectByIndex(3);
    

What is the use of Actions class in Selenium?

The Actions class in Selenium is used to perform advanced user interactions like mouse movements, key presses, drag and drop, and context clicks. It provides a way to build a sequence of actions and execute them in a single step.

import org.openqa.selenium.interactions.Actions;
    
    Actions actions = new Actions(driver);
    
    // Mouse hover
    WebElement menu = driver.findElement(By.id("menu"));
    actions.moveToElement(menu).perform();
    
    // Drag and drop
    WebElement source = driver.findElement(By.id("source"));
    WebElement target = driver.findElement(By.id("target"));
    actions.dragAndDrop(source, target).perform();
    
    // Right-click
    WebElement element = driver.findElement(By.id("element"));
    actions.contextClick(element).perform();
    

What is implicit wait in Selenium?

Implicit wait is a Selenium WebDriver mechanism that sets a default wait time for the WebDriver to poll the DOM for a certain duration when trying to find an element if it is not immediately available. It is applied globally and remains active for the entire duration of the WebDriver session.

// Setting implicit wait of 10 seconds
    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
    

What is an explicit wait in Selenium?

Explicit wait is a Selenium WebDriver mechanism that allows you to wait for a specific condition to occur before proceeding with the execution. It is applied to a particular element with a specified condition, offering more control compared to implicit waits.

import org.openqa.selenium.support.ui.WebDriverWait;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
    WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));
    

How do you capture screenshots in Selenium?

Capturing screenshots in Selenium can be done using the TakesScreenshot interface. It allows you to take a screenshot of the current browser window and save it to a desired location.

import org.openqa.selenium.OutputType;
    import org.openqa.selenium.TakesScreenshot;
    import org.apache.commons.io.FileUtils;
    
    File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File("screenshot.png"));
    

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

driver.findElement() returns the first WebElement that matches the locator. If no element is found, it throws a NoSuchElementException. driver.findElements() returns a list of all WebElements matching the locator. If no elements are found, it returns an empty list.

How do you handle exceptions in Selenium?

Handling exceptions in Selenium involves using try-catch blocks to catch specific WebDriver exceptions and implement appropriate error-handling mechanisms. Common exceptions include NoSuchElementException, TimeoutException, and ElementNotInteractableException. Proper exception handling ensures that tests can gracefully handle unexpected issues and provide meaningful error messages.

What is the use of JavaScriptExecutor in Selenium?

JavaScriptExecutor is an interface in Selenium that allows the execution of JavaScript code within the context of the browser. It is useful for performing actions that are not supported by the standard WebDriver API, such as scrolling the page, clicking on hidden elements, or retrieving properties directly from the DOM.

import org.openqa.selenium.JavascriptExecutor;
    
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
    
    // Click a hidden element
    WebElement hiddenElement = driver.findElement(By.id("hidden"));
    js.executeScript("arguments[0].click();", hiddenElement);
    

What is the difference between assert and verify in Selenium?

In Selenium, assert and verify are used to validate test conditions. Assert stops the test execution if the condition fails, marking the test as failed. Verify checks the condition and logs the failure but continues with the test execution. This allows the test to collect multiple failures before terminating.

How do you handle file uploads in Selenium?

Handling file uploads in Selenium is typically done by sending the file path to the file input element using the sendKeys() method. This simulates the action of selecting a file from the file system.

WebElement uploadElement = driver.findElement(By.id("upload"));
    uploadElement.sendKeys("C:\\path\\to\\file.txt");
    

What is TestNG and how is it used with Selenium?

TestNG is a testing framework inspired by JUnit and NUnit, designed to simplify a broad range of testing needs, from unit testing to integration testing. It provides advanced features like annotations, grouping, sequencing, parameterization, and parallel execution. When used with Selenium, TestNG helps organize and manage test cases efficiently, enabling better test reporting and execution control.

@Test
    public void testGoogleSearch() {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.google.com");
        // Test steps
        driver.quit();
    }
    

What is the difference between driver.navigate().to() and driver.get()?

driver.get() and driver.navigate().to() both navigate to a specified URL. However, navigate().to() is part of the navigation interface and provides additional capabilities like moving forward, backward, and refreshing the page, while get() is simpler and waits until the page is fully loaded before proceeding.

How do you perform parallel test execution in Selenium?

Parallel test execution in Selenium can be achieved using TestNG or JUnit frameworks in combination with Selenium Grid. TestNG allows configuring parallel execution through its XML configuration file, specifying the number of threads and test suites to run simultaneously. Selenium Grid facilitates the distribution of tests across multiple nodes, enabling concurrent execution on different browsers and platforms.

<suite name="Suite" parallel="tests" thread-count="2">
        <test name="Test1">
            <classes>
                <class name="com.example.TestClass1"/>
            </classes>
        </test>
        <test name="Test2">
            <classes>
                <class name="com.example.TestClass2"/>
            </classes>
        </test>
    </suite>
    

What is the use of DesiredCapabilities in Selenium?

DesiredCapabilities is a class in Selenium that is used to define the properties of the browser and the environment in which the tests will run. It allows you to set various configurations like browser name, browser version, platform, and other specific settings required for the test execution.

DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setBrowserName("chrome");
    capabilities.setVersion("89.0");
    capabilities.setPlatform(Platform.WINDOWS);
    
    WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities);
    

How do you handle AJAX calls in Selenium?

Handling AJAX calls in Selenium involves waiting for the asynchronous operations to complete before interacting with the elements that depend on them. This can be achieved using explicit waits to wait for specific conditions, such as the visibility or clickability of elements, or waiting for certain JavaScript conditions to be met.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("ajaxElement")));
    

What is headless browser testing?

Headless browser testing involves running tests on browsers without a graphical user interface. This is useful for running tests in environments where a UI is not necessary, such as continuous integration pipelines, and can lead to faster test execution. Popular headless browsers include Headless Chrome and Headless Firefox.

ChromeOptions options = new ChromeOptions();
    options.addArguments("--headless");
    WebDriver driver = new ChromeDriver(options);
    

How do you handle cookies in Selenium?

Handling cookies in Selenium involves using the WebDriver’s cookie management methods. You can add, delete, retrieve, and manage cookies using the manage().getCookies() and related methods.

// Adding a cookie
    Cookie cookie = new Cookie("key", "value");
    driver.manage().addCookie(cookie);
    
    // Retrieving all cookies
    Set<Cookie> cookies = driver.manage().getCookies();
    
    // Deleting a specific cookie
    driver.manage().deleteCookieNamed("key");
    
    // Deleting all cookies
    driver.manage().deleteAllCookies();
    

What is the difference between Selenium and QTP/UFT?

Selenium is an open-source framework primarily used for web application testing, supporting multiple programming languages and browsers. QTP (QuickTest Professional), now known as UFT (Unified Functional Testing), is a commercial tool developed by Micro Focus, supporting both web and desktop applications with a proprietary scripting language (VBScript). Selenium is more flexible and cost-effective, while UFT offers integrated features and support for a wider range of applications.

What is Fluent Wait in Selenium?

Fluent Wait in Selenium is a more advanced form of explicit wait that allows you to define the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. It also allows ignoring specific types of exceptions while waiting, providing greater flexibility in handling dynamic elements.

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(Duration.ofSeconds(30))
            .pollingEvery(Duration.ofSeconds(5))
            .ignoring(NoSuchElementException.class);
    
    WebElement element = wait.until(driver -> driver.findElement(By.id("elementId")));
    

What is the use of TestNG in Selenium?

TestNG is a testing framework that provides powerful features like annotations, parallel test execution, data-driven testing, and advanced reporting. When used with Selenium, TestNG helps organize test cases, manage test configurations, and execute tests efficiently, enhancing the overall testing process.

@Test
    public void testGoogleSearch() {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.google.com");
        // Test steps
        driver.quit();
    }
    

How do you handle dropdowns in Selenium?

Handling dropdowns in Selenium is done using the Select class. It allows selecting options by visible text, value, or index. Example:

import org.openqa.selenium.support.ui.Select;
    
    WebElement dropdown = driver.findElement(By.id("dropdownId"));
    Select select = new Select(dropdown);
    
    // Select by visible text
    select.selectByVisibleText("Option 1");
    
    // Select by value
    select.selectByValue("option2");
    
    // Select by index
    select.selectByIndex(3);
    

What is the difference between findElement() and findElements() in Selenium?

findElement() returns the first WebElement that matches the locator. If no element is found, it throws a NoSuchElementException. findElements() returns a list of all WebElements matching the locator. If no elements are found, it returns an empty list.

How do you handle alerts in Selenium?

Handling alerts in Selenium involves using the Alert interface provided by WebDriver. You can switch to the alert, accept or dismiss it, and retrieve its text. For example:

// Switch to alert
    Alert alert = driver.switchTo().alert();
    
    // Get alert text
    String alertText = alert.getText();
    
    // Accept the alert
    alert.accept();
    
    // Dismiss the alert
    alert.dismiss();
    

What is the Page Factory in Selenium?

Page Factory is an implementation of the Page Object Model (POM) in Selenium. It uses annotations to define and initialize web elements, making the code more readable and maintainable. The @FindBy annotation is commonly used to locate elements, and the PageFactory.initElements() method initializes them.

import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import org.openqa.selenium.support.PageFactory;
    
    public class LoginPage {
        WebDriver driver;
        
        @FindBy(id="username")
        WebElement username;
        
        @FindBy(id="password")
        WebElement password;
        
        @FindBy(id="login")
        WebElement loginButton;
        
        public LoginPage(WebDriver driver){
            this.driver = driver;
            PageFactory.initElements(driver, this);
        }
        
        public void login(String user, String pass){
            username.sendKeys(user);
            password.sendKeys(pass);
            loginButton.click();
        }
    }
    

What is the use of JavaScriptExecutor in Selenium?

JavaScriptExecutor is an interface in Selenium that allows the execution of JavaScript code within the context of the browser. It is useful for performing actions that are not supported by the standard WebDriver API, such as scrolling the page, clicking on hidden elements, or retrieving properties directly from the DOM.

import org.openqa.selenium.JavascriptExecutor;
    
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
    
    // Click a hidden element
    WebElement hiddenElement = driver.findElement(By.id("hidden"));
    js.executeScript("arguments[0].click();", hiddenElement);
    

What is the difference between driver.close() and driver.quit()?

driver.close() closes the current browser window that the driver is controlling, whereas driver.quit() closes all browser windows opened by the WebDriver and ends the WebDriver session. quit() is useful for cleanup after all tests have been executed.

What is the difference between Selenium and QTP/UFT?

Selenium is an open-source framework primarily used for web application testing, supporting multiple programming languages and browsers. QTP (QuickTest Professional), now known as UFT (Unified Functional Testing), is a commercial tool developed by Micro Focus, supporting both web and desktop applications with a proprietary scripting language (VBScript). Selenium is more flexible and cost-effective, while UFT offers integrated features and support for a wider range of applications.

What are implicit and explicit waits in Selenium?

Selenium provides two types of waits to handle synchronization issues:

  • Implicit Wait: Sets a default wait time for the WebDriver to poll the DOM for a certain duration when trying to find an element if it is not immediately available.
  • Explicit Wait: Allows you to wait for a specific condition to occur before proceeding, offering more granular control over synchronization.

How do you handle file uploads in Selenium?

Handling file uploads in Selenium is typically done by sending the file path to the file input element using the sendKeys() method. This simulates the action of selecting a file from the file system.

WebElement uploadElement = driver.findElement(By.id("upload"));
    uploadElement.sendKeys("C:\\path\\to\\file.txt");
    

What is the use of DesiredCapabilities in Selenium?

DesiredCapabilities is a class in Selenium that is used to define the properties of the browser and the environment in which the tests will run. It allows you to set various configurations like browser name, browser version, platform, and other specific settings required for the test execution.

DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setBrowserName("chrome");
    capabilities.setVersion("89.0");
    capabilities.setPlatform(Platform.WINDOWS);
    
    WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities);
    

What is TestNG and how is it used with Selenium?

TestNG is a testing framework that provides powerful features like annotations, parallel test execution, data-driven testing, and advanced reporting. When used with Selenium, TestNG helps organize test cases, manage test configurations, and execute tests efficiently, enhancing the overall testing process.

@Test
    public void testGoogleSearch() {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.google.com");
        // Test steps
        driver.quit();
    }
    

What is Fluent Wait in Selenium?

Fluent Wait in Selenium is a more advanced form of explicit wait that allows you to define the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. It also allows ignoring specific types of exceptions while waiting, providing greater flexibility in handling dynamic elements.

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(Duration.ofSeconds(30))
            .pollingEvery(Duration.ofSeconds(5))
            .ignoring(NoSuchElementException.class);
    
    WebElement element = wait.until(driver -> driver.findElement(By.id("elementId")));
    

What is the difference between assert and verify in Selenium?

In Selenium, assert and verify are used to validate test conditions. Assert stops the test execution if the condition fails, marking the test as failed. Verify checks the condition and logs the failure but continues with the test execution. This allows the test to collect multiple failures before terminating.

How do you perform parallel test execution in Selenium?

Parallel test execution in Selenium can be achieved using TestNG or JUnit frameworks in combination with Selenium Grid. TestNG allows configuring parallel execution through its XML configuration file, specifying the number of threads and test suites to run simultaneously. Selenium Grid facilitates the distribution of tests across multiple nodes, enabling concurrent execution on different browsers and platforms.

<suite name="Suite" parallel="tests" thread-count="2">
        <test name="Test1">
            <classes>
                <class name="com.example.TestClass1"/>
            </classes>
        </test>
        <test name="Test2">
            <classes>
                <class name="com.example.TestClass2"/>
            </classes>
        </test>
    </suite>
    

What is Selenium Grid and how does it work?

Selenium Grid is a tool that allows you to run tests on different machines and browsers simultaneously, enabling parallel execution. It consists of a Hub and multiple Nodes. The Hub acts as a central point where tests are sent, and the Nodes are the machines where the tests are executed. This setup helps in reducing the overall test execution time and ensures cross-browser compatibility.

How do you handle frames and windows in Selenium?

Handling frames and windows in Selenium involves switching the WebDriver’s context to the desired frame or window. For frames, you can switch using the frame’s index, name, or WebElement. For windows, you can switch based on window handles. Example for frames:

// Switching to a frame by index
    driver.switchTo().frame(0);
    
    // Switching back to the default content
    driver.switchTo().defaultContent();
    
    // Switching to a window
    String mainWindow = driver.getWindowHandle();
    for(String handle : driver.getWindowHandles()) {
        if(!handle.equals(mainWindow)) {
            driver.switchTo().window(handle);
            break;
        }
    }
    

What is the Page Object Model (POM) in Selenium?

The Page Object Model (POM) is a design pattern in Selenium that creates an object repository for web UI elements. Each web page in the application is represented by a separate class, and the elements on the page are defined as variables within the class. POM enhances test maintenance and reduces code duplication by separating the test scripts from the page-specific code.

How do you perform data-driven testing in Selenium?

Data-driven testing in Selenium involves separating test data from test scripts, allowing the same test to run multiple times with different data sets. This can be achieved using external data sources like Excel, CSV, XML, or databases. Frameworks like TestNG or JUnit can be integrated with Selenium to parameterize tests and iterate through data sets.

What is the difference between driver.navigate().to() and driver.get()?

driver.get() and driver.navigate().to() both navigate to a specified URL. However, navigate().to() is part of the navigation interface and provides additional capabilities like moving forward, backward, and refreshing the page, while get() is simpler and waits until the page is fully loaded before proceeding.

How do you handle multiple windows in Selenium?

Handling multiple windows in Selenium involves using window handles to switch the WebDriver’s context to the desired window. You can retrieve all window handles and switch between them as needed. Example:

String mainWindow = driver.getWindowHandle();
    
    // Click a link that opens a new window
    driver.findElement(By.linkText("Open New Window")).click();
    
    // Get all window handles
    Set<String> allWindows = driver.getWindowHandles();
    
    for(String handle : allWindows){
        if(!handle.equals(mainWindow)){
            driver.switchTo().window(handle);
            // Perform actions on the new window
            driver.close();
        }
    }
    
    // Switch back to the main window
    driver.switchTo().window(mainWindow);
    

What is the use of Actions class in Selenium?

The Actions class in Selenium is used to perform advanced user interactions like mouse movements, key presses, drag and drop, and context clicks. It provides a way to build a sequence of actions and execute them in a single step.

import org.openqa.selenium.interactions.Actions;
    
    Actions actions = new Actions(driver);
    
    // Mouse hover
    WebElement menu = driver.findElement(By.id("menu"));
    actions.moveToElement(menu).perform();
    
    // Drag and drop
    WebElement source = driver.findElement(By.id("source"));
    WebElement target = driver.findElement(By.id("target"));
    actions.dragAndDrop(source, target).perform();
    
    // Right-click
    WebElement element = driver.findElement(By.id("element"));
    actions.contextClick(element).perform();
    

How do you handle AJAX calls in Selenium?

Handling AJAX calls in Selenium involves waiting for the asynchronous operations to complete before interacting with the elements that depend on them. This can be achieved using explicit waits to wait for specific conditions, such as the visibility or clickability of elements, or waiting for certain JavaScript conditions to be met.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("ajaxElement")));
    

What is headless browser testing?

Headless browser testing involves running tests on browsers without a graphical user interface. This is useful for running tests in environments where a UI is not necessary, such as continuous integration pipelines, and can lead to faster test execution. Popular headless browsers include Headless Chrome and Headless Firefox.

ChromeOptions options = new ChromeOptions();
    options.addArguments("--headless");
    WebDriver driver = new ChromeDriver(options);
    

How do you handle cookies in Selenium?

Handling cookies in Selenium involves using the WebDriver’s cookie management methods. You can add, delete, retrieve, and manage cookies using the manage().getCookies() and related methods.

// Adding a cookie
    Cookie cookie = new Cookie("key", "value");
    driver.manage().addCookie(cookie);
    
    // Retrieving all cookies
    Set<Cookie> cookies = driver.manage().getCookies();
    
    // Deleting a specific cookie
    driver.manage().deleteCookieNamed("key");
    
    // Deleting all cookies
    driver.manage().deleteAllCookies();
    

What is the difference between driver.close() and driver.quit() in Selenium?

driver.close() closes the current browser window that the driver is controlling, whereas driver.quit() closes all browser windows opened by the WebDriver and ends the WebDriver session. quit() is useful for cleanup after all tests have been executed.

What is the Page Factory in Selenium?

Page Factory is an implementation of the Page Object Model (POM) in Selenium. It uses annotations to define and initialize web elements, making the code more readable and maintainable. The @FindBy annotation is commonly used to locate elements, and the PageFactory.initElements() method initializes them.

import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import org.openqa.selenium.support.PageFactory;
    
    public class LoginPage {
        WebDriver driver;
        
        @FindBy(id="username")
        WebElement username;
        
        @FindBy(id="password")
        WebElement password;
        
        @FindBy(id="login")
        WebElement loginButton;
        
        public LoginPage(WebDriver driver){
            this.driver = driver;
            PageFactory.initElements(driver, this);
        }
        
        public void login(String user, String pass){
            username.sendKeys(user);
            password.sendKeys(pass);
            loginButton.click();
        }
    }
    

What is the use of JavaScriptExecutor in Selenium?

JavaScriptExecutor is an interface in Selenium that allows the execution of JavaScript code within the context of the browser. It is useful for performing actions that are not supported by the standard WebDriver API, such as scrolling the page, clicking on hidden elements, or retrieving properties directly from the DOM.

import org.openqa.selenium.JavascriptExecutor;
    
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
    
    // Click a hidden element
    WebElement hiddenElement = driver.findElement(By.id("hidden"));
    js.executeScript("arguments[0].click();", hiddenElement);