Wednesday 24 July 2013

How to handle StaleElementReferenceException?


Why StatleElementReferenceException is thrown?


StatleElementReferenceException indicates that a reference to an element is stale, means that element no longer appears on the DOM of the page.

For example let we consider the following code,

                List <WebElement> alllinks = driver.findElements(By.tagName("a"));

for(WebElement link : alllinks) {
link.click(); // It may cause StatleElementReferenceException 
                         driver.navigate().back();
}

Here the reference variable 'alllinks' has the reference of all the WebElements, those has anchor(//a) tag. Coming to below, the 'for' loop clicks on the each WebElement, then navigates to its corresponding page and comes back to the original page. Due to this navigation/refresh DOM references might be changed. But the reference variable 'alllinks' holds the previous references of WebElements. Now the reference of the element becomes 'stale'. In this case the StaleElementReferenceException is thrown.

How to handle StatleElementReferenceException?



You can avoid this StatleElementReferenceException be having following style of code,

             int sizeOfAllLinks = driver.findElements(By.tagName("a")).size();

            for (int index=0; index<sizeOfAllLinks; i++ ) {
                  getElementWithIndex(By.tagName("a"), index).click();
                  driver.navigate().back();
            }


            public WebElement getElementWithIndex(By by, int index) {
                  return webDriver.findElements(by).get(index);
            }

3 comments:


  1. Best place to learn Appium Android IOS Automation Testing Training in Chennai

    Go for Appium training in chennai for real time mobile automation testing training with real time project support.
    Mr. Vishwa is a best person who can teach and develop people in Appium and Selenium,Coded UI Automation Tools with real time scenarios You can contact 8122241286 for Best APPIUM and selenium Training in Chennai

    ReplyDelete
  2. Appium Training in chennai
    We provides Best Appium Training in Chennai with real time project assistance by our leading Appium mobile App Automation testing architect
    For Free Live Demo @ Call to 8122241286.
    Appium ,Selenium,Mobile Automation Testiing using Android and IOS
    www.thecreatingexperts.com
    Appium training in chennai

    ReplyDelete
  3. El Cortez Casino Resort, El Cortez - Mapyro
    El Cortez Hotel & Casino 용인 출장마사지 is a community of 4 people with a number of 창원 출장샵 disabilities. The resort features a 여수 출장안마 health 제주도 출장안마 and 세종특별자치 출장샵 safety net of over 300,000

    ReplyDelete