Krishna
Krishna

Reputation: 153

Getting stale element reference: element is not attached to the page document exception

In my application, when i open the page,left hand side are displayed list of tabs.

By default,one tab is opened status and other tabs are closed status,so i am looking to find the opened status tab class name and clicked the tab, it has closed,then had to give the another tab id to open.

While executing the code,I am getting the "stale element reference: element is not attached to the page document" exception.

I have tried with implicit wait option as well.

Could any one please help on that issue to resolve?

driver.manage().timeouts().implicitlyWait(1000,TimeUnit.SECONDS);

                  WebElement element5 = driver.findElement(By.className("TopItemActive"));
                  if(element5.isEnabled())
                  {
                  element5.click();
                  }

                  driver.manage().timeouts().implicitlyWait(2000,TimeUnit.SECONDS);
                WebElement element6 = driver.findElement(By.id("id_16_cell"));        
                element6.click();
                System.out.println("Tab opened");

Upvotes: 0

Views: 4884

Answers (1)

Andreas Waldahl
Andreas Waldahl

Reputation: 302

My guess is that your tabs are created and removed with JavaScript. What Webdriver does is to download the webpage and store it in the instance. If something is changed due to javascript webdriver isnt always aware of it.

This could work as a simple solution

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.refreshed(ExpectedConditions.elementToBeClickable(by)));

What i have found is there isnt much to do about it. I catch the exception thrown and try again. So I created a new function for "click"

public String click(By by){

   String text = "";

   driver.manage().timeouts().implicitlyWait( 5, TimeUnit.SECONDS );
   boolean unfound = true;
   int tries = 0;
   while ( unfound && tries < 3 ) {
     tries += 1;
     try {
       wait.until(ExpectedConditions.refreshed(ExpectedConditions.visibilityOfElementLocated(by)));
       text = driver.findElement(by).click();
       unfound = false;
       logger.info("Click element "+stripBy(by));
     } catch ( StaleElementReferenceException ser ) {
       logger.error( "ERROR: Stale element exception. " + stripBy(by) );
     } catch ( NoSuchElementException nse ) {
       logger.error( "ERROR: No such element exception. " + stripBy(by)+"\nError: "+nse );
     } catch ( Exception e ) {
       logger.error( e.getMessage() );
     }
   }

   if(unfound)
   Assert.assertTrue(false,"Failed to locate element by locator " + stripBy(by));

   return text;

}

Upvotes: 2

Related Questions