top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Fixing Most Common Exceptions in Selenium WebDriver

An exception is when something unexpected happens in a program that stops it from running normally. While using selenium there are many common exceptions that can happen. In this article, we will discuss about few of them and ways to deal with such exceptions.






ElementNotSelectableException

The ElementNotSelectableException in Selenium occurs when you're trying to interact with an element that's present in the DOM but can't be selected. For instance, you might run into this issue when dealing with a script element.


Solution:

  • Try alternative methods to select the element, like selectByIndex or selectByVisibleText.

// Try selecting the element using alternative methods
  WebElement dropdown = driver.findElement(By.id("dropdown"));
  Select select = new Select(dropdown);
 // Instead of directly selecting by value or text, try selecting by index
  select.selectByIndex(2);
  • Add a wait command to pause execution until the element becomes clickable.


WebDriverWait wait = new WebDriverWait(driver, 10);
// Wait until the dropdown element is clickable    wait.until(ExpectedConditions.elementToBeClickable(By.id("dropdown")));
// Now you can interact with the dropdown safely
 dropdown.click();

ElementNotInteractableException

The ElementNotInteractableException arises when an element exists in the DOM but cannot be interacted with, such as being unable to click on it or input text. This typically occurs when the element is either hidden or disabled.


Solution:

  • Utilize Explicit wait to wait until the element becomes visible or clickable.

// Waiting until the element is visible or clickable using Explicit wait
WebElement element1 = wait.until(ExpectedConditions.elementToBeClickable(By.id("elementId")));
        element1.click();	
  • Use the Actions class to scroll until the element becomes displayed.

//  Scrolling until the element gets displayed using the Actions class
 WebElement element2 = driver.findElement(By.id("elementId"));
        actions.moveToElement(element2).perform();
        element2.click();
  • Employ JS Executor to directly interact with the DOM.

// Using JS Executor to interact directly with the DOM
        WebElement element3 = driver.findElement(By.id("elementId"));
        jsExecutor.executeScript("arguments[0].click();", element3);

ElementNotVisibleException

Selenium raises an ElementNotVisibleException when an element exists in the DOM but remains hidden from the user's view.


Solution:

  • Try to craft distinctive locators that exclusively match a single element.

// Trying to write unique locators that match with a single element only
        WebElement uniqueElement = driver.findElement(By.xpath("//input[@id='uniqueId']"));

  • Implement explicit wait to ensure the element becomes visible or clickable before proceeding with interaction.

// Waiting until the element is visible or clickable using explicit wait
        WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//button[@id='submitButton']")));

NoSuchElementException

This is the most common exception in selenium, a subclass of the NotFoundException class in Selenium, arises most frequently from the findElement() method of Selenium WebDriver. It occurs when the locators specified in the Selenium script fail to find the element within the DOM.


Solution:

  • Double-check the locator by inspecting the browser to confirm if the element exists in the DOM and use isDisplayed() method to check before interacting with the element

 WebElement element = driver.findElement(By.id("exampleId"));  
        if(element.isDisplayed()) {
			element.click();
            System.out.println("Element found successfully!");
        } else {
            System.out.println("Element not found in DOM");
        }
  • Employ explicit wait to ensure the element loads before interacting with it.

	 
// Explicitly wait for the element to be present and visible
 WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("exampleId")));
// Perform actions on the element
 element.click();	

StaleElementReferenceException

This exception arises when the element previously referenced by the locator is no longer available in the DOM or has become stale. It occurs as a runtime issue when the page dynamically loads, removing the referenced element entirely from the DOM, causing it to become stale.


Solution:

  • Reload the page before interacting with the element that triggers the StaleElementException.

try {
       // Locate the element that may cause StaleElementException
            WebElement element = driver.findElement(By.id("exampleId"));
        // Perform some action on the element
            element.click();
        } catch(org.openqa.selenium.StaleElementReferenceException ex) {
         // If StaleElementException occurs, refresh the page
            driver.navigate().refresh();
          // Now try to locate the element again
            WebElement refreshedElement =                     		driver.findElement(By.id("exampleId"));
            // Perform action on the refreshed element
            refreshedElement.click();
        }
  • Employ a try-catch block to manage the exception and retry locating the element within the catch block.

try {
            // Locate the element that may cause StaleElementException
            WebElement element = driver.findElement(By.id("exampleId"));
            // Perform some action on the element
            element.click();
        } catch(org.openqa.selenium.StaleElementReferenceException ex) {
            // Handle StaleElementException
            System.out.println("StaleElementException occurred. Retrying to locate the element...");
            // Attempt to locate the element again
            WebElement retryElement = driver.findElement(By.id("exampleId"));
            // Perform action on the element after retrying
            retryElement.click();
        }

WebDriverException

This exception arises when the WebDriver attempts to execute actions immediately after closing the driver session.

Solution:

  • Employ driver.close() once all tests within the suite are completed, rather than at the individual test level.

  @BeforeSuite
    public void setUp() {
        driver = new ChromeDriver();
    }

    @Test
    public void test1() {
        // Test steps
    }

    @Test
    public void test2() {
        // Test steps
    }

    @AfterSuite
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
  • If utilizing TestNG, implement driver.close() within @AfterSuite instead of @AfterTest.

 @BeforeSuite
    public void setUp() {
        driver = new ChromeDriver();
    }

    @Test
    public void test1() {
        // Test steps
    }

    @Test
    public void test2() {
        // Test steps
    }

    @AfterTest
    public void afterTest() {
        // This method will be executed after each test method
    }

    @AfterSuite
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }

TimeOutException

In Selenium, a TimeOutException arises when a command exceeds the specified wait time to prevent the ElementNotVisible Exception. Environmental factors like slow internet speed or prolonged web application loading can impede the complete loading of the element intended for interaction. In such scenarios, when the WebDriver attempts to locate the element on the webpage, a TimeoutException occurs.


Solution:

  • Manually assess the load time of the web element and adjust the wait duration accordingly.

  • Incorporate explicit wait using JavaScript executor until the page is fully loaded.

// Add explicit wait using JavaScript executor until the page is loaded
        WebDriverWait wait = new WebDriverWait(driver, 30);
        wait.until(webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
        
        // Perform further actions after the page is fully loaded
        // For example, find and interact with the element
        driver.findElement(By.id("exampleId")).click();
  • Consider utilizing alternative locators such as CSS Selector or XPath to locate the element.

 // Use alternative locators like CSS Selector or XPath
        WebDriverWait wait = new WebDriverWait(driver, 30);
        WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("css-selector-of-element")));
        
        // Perform actions on the element
        element.click();

SessionNotFoundException

SessionNotFoundException arises when the WebDriver attempts to execute actions on the web application following the closure of the browser, or when the browser session is inaccessible.


Solution:

  • To address these exceptions, it's essential to review our code meticulously, ensuring that the browser isn't inadvertently closed.

  • Ensure that the browser remains open throughout the execution and is only closed at the conclusion of the execution process.


NoSuchWindowException

NoSuchWindowException is thrown by Selenium when the WebDriver is unable to locate the intended browser window or tab using the provided window handle or name. This can happen if the targeted window or tab is absent, has been closed during execution, or hasn't fully loaded.


Solution:

  • Verify the accuracy of the window handle or name being utilized.


        String windowHandle = "WINDOW_HANDLE_ID";
        
        try {
            // Switch to the window using the provided handle or name
            driver.switchTo().window(windowHandle);
            // Perform actions on the window
            // Example: driver.findElement(By.id("elementId")).click();
        } catch (NoSuchWindowException e) {
            System.out.println("No such window found. Please verify the window handle or name.");
        }
        
  • Wait for the browser window or tab to finish loading entirely before switching the WebDriver to the desired window instance.

  // Wait for the new window to appear and completely load
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until((ExpectedCondition<Boolean>) webDriver -> !webDriver.getWindowHandles().isEmpty());
        
        // Switch to the new window
        for (String windowHandle : driver.getWindowHandles()) {
            driver.switchTo().window(windowHandle);
            // Check if the window has completely loaded
            if (driver.getTitle().equals("Expected Title")) {
                // Perform actions on the new window
                // Example: driver.findElement(By.id("elementId")).click();
                break;
            }
        }
        

I hope this article is helpful to you.Feel free to explore my other blog posted on Agile Methodology and the blog link is provided here for your reference.("https://www.numpyninja.com/post/agile-standards-and-best-practices-for-sdet").

Appreciate your time and interest in reading!

55 views0 comments

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page