How can I use selenium WebDriver in Java programming language for Checking a specific element?

43    Asked by DavidWHITE in QA Testing , Asked on Apr 10, 2024

I am currently engaged in a particular task that is related to automating the testing of a web-based application by using the Selenium WebDriver in Java. In this particular task, I need to check if a specific element, such as a button or input fields, exists on the web page before proceeding with furthermore action. How can I implement a check to verify the existence of this element by using selenium WebDriver in Java programming language? 

Answered by David

 In the context of Selenium, here is how you can implement a check to verify if an element exists on a particular web-based page by using the Selenium WebDriver in Java programming language:-


Import org.openqa.selenium.By;
Import org.openqa.selenium.WebDriver;
Import org.openqa.selenium.WebElement;
Import org.openqa.selenium.chrome.ChromeDriver;
Public class ElementExistenceCheck {
    Public static void main(String[] args) {
        // Set the path to the ChromeDriver executable
        System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
        // Initialize the ChromeDriver instance
        WebDriver driver = new ChromeDriver();
        // Navigate to the desired webpage
        Driver.get(https://www.example.com);
        // Find the element using a locator (e.g., ID, class name, XPath)
        By elementLocator = By.id(“elementId”); // Replace “elementId” with the actual ID of the element
        // Check if the element exists on the page
        Boolean isElementPresent = isElementPresent(driver, elementLocator);
        // Print the result of the existence check
        If (isElementPresent) {
            System.out.println(“Element exists on the page.”);
        } else {
            System.out.println(“Element does not exist on the page.”);
        }
        // Close the WebDriver instance
        Driver.quit();
    }
    // Custom method to check if an element exists
    Public static boolean isElementPresent(WebDriver driver, By locator) {
        Try {
            // Attempt to find the element using the specified locator
            WebElement element = driver.findElement(locator);
            // If element is found, return true
            Return element != null;
        } catch (org.openqa.selenium.NoSuchElementException e) {
            // If element is not found, catch the exception and return false
            Return false;
        }
    }
}

You can replace the “elementId” with the actual ID, class name, or Xpath of the element which you want to check for existence in the web-based page.



Your Answer

Interviews

Parent Categories