How To Handle Stale Element Exception In Selenium WebDriver

How-To-Handle-Stale-Element-Exception-In-Selenium-WebDriver

Stale element exception is the most common type of exceptions which is occurred in selenium web driver, it is showing error as “Exception in thread “main” org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

stale-element-exceptions

What Is The Reason Behind This Error: Major reason behind this type of error is that actually while the page reloading again after some action then it is not attached with the Document Object Model(DOM) and when driver is searching for that element it is not found on the page because page is ultimately not loading the whole page rather than just load through “ajax” and only content part is overloaded.

Example: The best example of Stale element is that in the below page of  Jquery UI page https://jqueryui.com/datepicker/#default user easily found each element in current section of calendar but when user clicks on “next” and “previous” button whole page is not reloading and it throws error as “Stale element exception” because when user clicks on next/previous button the whole page is not reloading and only sections are loaded through AJAX, below is the code in which you can find the “stale element exception”.

stale-element-exceptions


package webhandling;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class CalendarTest {
public static void main(String[] args) {

System.setProperty(“webdriver.chrome.driver”,System.getProperty(“user.dir”)+”\\src\\test\\resources\\executables\\chromedriver.exe”);
WebDriver driver= new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get(“https://jqueryui.com/datepicker/”);
driver.manage().window().maximize();
/* Switch to frame div */
driver.switchTo().frame(driver.findElement(By.xpath(“//iframe[@class=’demo-frame’]”)));
WebElement dpicker_textbox = driver.findElement(By.xpath(“//input[@id=’datepicker’][@class=’hasDatepicker’]”));
dpicker_textbox.click();
String month=driver.findElement(By.className(“ui-datepicker-month”)).getText();
String year= driver.findElement(By.className(“ui-datepicker-year”)).getText();
/* Pick 20 September 2017 i.e. any date of the current month */
List<WebElement> day_lists = driver.findElements(By.xpath(“//*[@data-handler=’selectDay’]”));

for(WebElement days:day_lists)
{
if(days.getText().equals(“20”))
{
days.click();
String day=days.getText();
System.out.println(“Selected Date=”+day+month+year);

}
}
driver.findElement(By.xpath(“//input[@id=’datepicker’][@class=’hasDatepicker’]”)).clear();
/* Select Previous/Next Date i.e. Date 10-9-2016 */
int setday=10;
int setmonth=9;
int setyear=2015;
System.out.println(“Set Date Value For Auto Selection=”+setmonth+’/’+setday+’/’+setyear);
driver.findElement(By.xpath(“//input[@id=’datepicker’][@class=’hasDatepicker’]”)).click();
String month_name=driver.findElement(By.className(“ui-datepicker-month”)).getText();
int month_val=getMonth_No(month_name);
String year_no= driver.findElement(By.className(“ui-datepicker-year”)).getText();
System.out.println(“Month=”+month_val+”Year_No=”+year_no);
WebElement prev_button= driver.findElement(By.xpath(“//*[@data-handler=’prev’]”));
WebElement next_button= driver.findElement(By.xpath(“//*[@data-handler=’next’]”));
int diff = setyear-Integer.parseInt(year_no);
System.out.println(“Year difference=”+diff);
if(diff<0)
{
for(int i=month_val;i>1;i–)
{
prev_button= driver.findElement(By.xpath(“//*[@data-handler=’prev’]”));
prev_button.click();
}
for(int j=diff;j<0;j++)
{
for(int k=1;k<=12;k++)
{
prev_button= driver.findElement(By.xpath(“//*[@data-handler=’prev’]”));
prev_button.click();

}

}
}
else if(diff>0){

for(int i=month_val;i>=1;i–)
{
prev_button= driver.findElement(By.xpath(“//*[@data-handler=’prev’]”));
prev_button.click();
}
for(int i=0;i<diff;i–)
{
for(i=1;i<=12;i++)
{
next_button=driver.findElement(By.xpath(“//*[@data-handler=’next’]”));
next_button.click();
}
}
}
String curmonth_name=driver.findElement(By.className(“ui-datepicker-month”)).getText();
int curmonth_val=getMonth_No(curmonth_name);
System.out.println(curmonth_val);
if(curmonth_val< setmonth)
{
for(int i=curmonth_val;i<setmonth;i++)
{
// next_button=driver.findElement(By.xpath(“//*[@data-handler=’next’]”));
next_button.click();
}
}
else if(curmonth_val>setmonth){
for(int i=curmonth_val;i>setmonth;i–)
{
// prev_button= driver.findElement(By.xpath(“//*[@data-handler=’prev’]”));
prev_button.click();
}
}
System.out.println(“Conditional Statement End…”);

List<WebElement> days_lists = driver.findElements(By.xpath(“//*[@data-handler=’selectDay’]”));
month=driver.findElement(By.className(“ui-datepicker-month”)).getText();
year= driver.findElement(By.className(“ui-datepicker-year”)).getText();
for(WebElement days_count:days_lists)
{
if((days_count.getText()).equals(Integer.toString(setday)))
{
days_count.click();
String day=days_count.getText();

System.out.println(“Selected Date=”+day+month+year);

}
}

}

public static int getMonth_No(String MonthStringVal)
{
int i;
String [] month_names={“January”,”February”,”March”,”April”,”May”,”June”,”July”,”Aug”,”September”,”October”,”November”,”December”};
for( i=0;i<month_names.length;i++)
{
if(month_names[i].equals(MonthStringVal))
break;
}
return i+1;

}
}


In the above-highlighted text if we can not initiate the locator again on the code section it will throw exceptions but if we remove the comment on the above two highlighted red color commented code then program will run absolutely fine.

Best Solution:  the Best solution is that you can re-initiate the same locator in the loop/code section again like above example “prev_button” and “next button” re-initialize. 

Now It will work fine if you are looking for more solutions and scenario about “Stale Element Exception” read this post of seleniumhq.org  official site blog Read More

If you are facing any difficulty and facing any type of “Stale Element Exception” error do write your issue in the below comment box, would try to answer and solve the issue ASAP.

share this article on social media and tag the friend who are facing such type of issues in selenium.

 

For your Success,

Adil

Adil

My Name is Mohammad Adil and I am a tech enthusiastic, a technical blogger, motivational speaker, trainer and passionate quality analyst with over 5+ years of experience in software testing field as well as information technology field. I worked with various reputed CMM level companies and currently working with a well-reputed product development company.