LayoutTitle

Hoverable Dropdown

Tuesday, February 9, 2021

How to solve Stale Element Reference exception in Selenium Webdriver

What is Stale Element?

Means a Stale element points to any of the GUI Object, which is not present any more.

What is the main Cause?

When an GUI Object was in DOM initially, later point in time during that Object become stale as it might not have present in Document Object Model (DOM).

How to catch stale elements/objects?

Using StaleElementReferenceException. This exception is cuases whenever an element is not present in the DOM, or deleted.

Are there any ways to handle? Yes, below are options to resolve the Stale elements.

1.     Page refresh and verifying again for the same element/object.

2.     Implement using Exception Handling method

3.     Use the point 2 using Iteration/loop statement based on the application behavior

4.     Explicit wait

 

Example for point 1:

       //refresh page

      driver.navigate().refresh();


Example for point 2:

       WebElement staleEle = driver.findElement(By.id("UserName"));
       try{
             staleEle.sendKeys("Selenium");
          }catch(StaleElementReferenceException e){
         staleEle = driver.findElement(By.id("UserName"));
         staleEle.sendKeys("Selenium");
         }


Example for point 3:

       
    for(int i =0;i<=3; i++){
        WebElement staleEle = driver.findElement(By.id("UserName"));
               try{
                     staleEle.sendKeys("Selenium");
                  }catch(StaleElementReferenceException e){
             staleEle = driver.findElement(By.id("UserName"));
             staleEle.sendKeys("Selenium");
         }
}


Example for point 4: 

WebDriverWait wait= new WebDriverWait(driver, 10);

      wait.until(ExpectedConditions.presenceOfElementLocated(By.id("UserName")));

 

 

 

 

 

 

 

 

No comments:

Post a Comment