PAGE 37: STALE EXCEPTION IN SELENIUM WEBDRIVER

Literary meaning of Stale: Old,decayed, no longer fresh… Exactly that is what referenced here.

Stale Element – An element that is found on a web page referenced as a WebElement in WebDriver then the DOM changes (probably due to JavaScript functions) that WebElement goes stale.
When you try to interact with the staled WebElement, the StaleElementException is thrown.
Another probable reason would be that the WebElement that is referenced had been deleted while DOM changes.

Example:

//Referencing an Element as WebElement on a web page with Id as a locator
WebElement assertSelenium = driver.findElement(By.Id("assert"))
//Accessing the WebElement
assertSelenium.click();


If Javascript updates the page between the findElement call and the click call then It will throw a StaleElementException.

This might not occur often, but when you get to know that the website that you are automating has lot of JavaScripts calls or AJAX calls then assume that this StaleElement Exception will occur sometime and its better to be cautious while scripting.

Mostly we will be working sitting inside a framework(DataDriven, Hybrid) what ever..

All the WebDrive API’s will be wrapped and we will use the framework API while scripting. Shortly a DSL While doing so its better to wrap it as below


public boolean Click(By by) {
boolean status = false;
for(int i=0; i<3;i++)
try {
driver.findElement(by).click();
status = true;
break;
} catch(StaleElementException e) {
}
return status;
}

public boolean Click(By by) {
boolean status = false;

//&lt; stands for the less-than sign ( < ) and &gt; stands for the greater-than sign ( > )

for(int i=0; i&lt;3;i++)
try {
driver.findElement(by).click();
status = true;
break;
} catch(StaleElementException e) {
}
return status;
}


The above code snippet should work and prevent us from the StaleElementException.
We have used for loop here to keep on trying for at least 3 times and once it is found we break the loop and come out other wise it will try for another time until max of 3 times. While its failing to find on the first attempt due to the DOM changes it should get succeeded while trying second time.

Another suggestion would be to try the below idea of referencing the locator as a string and using it.


for(int i = 1; i &lt;= 5; i++) {
String locator = String.format("div#someId", i);
WebElement assertSelenium = driver.findElement(By.cssSelector(locator));
System.out.println(assertSelenium.getText());
}


No comments:

About Me

My photo
Pune, Maharastra, India
You can reach me out at : jimmiamrit@gmail.com