Pages

How To Handle staleelementreferenceexception Selenium Webdriver

staleelementreferenceexception

There are many different exceptions In selenium webdriver software testing tool. I have described 5 of them on THIS PAGE which we are facing frequently. One more webdriver exception Is stale element reference exception. I think some of you have faced or will face this exception when you run selenium webdriver test for your softwareweb application. Just recently I have faced this exception In my test with exception message as bellow.

Exception :

org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up

Command duration or timeout: 10.03 seconds

What Is StaleElementReferenceException?

Stale means old or we can say no longer fresh element. Let me describe you In very simple words. Example : You have a search text box on software web page. When you search for some keyword, text box's position get changed on page. So In this case, Look and feel, Identifiers etc. of text box will remain same but what Internally happened Is -> JS library has deleted previous text box and replaced It with new same text box. So now If you will go to use same text box using previously located reference In your software test, You will get StaleElementReferenceException In console.

If you will run bellow given example, It will throw StaleElementReferenceException.

This Is just example. You can have different situation or scenario. This will happen only some times but you must know how to resolve It.There may be some other reasons too for this exception. Now let us try to resolve or handle this exception.

So Exception Is generating on Search_Box.clear(); line because software web application page has been refreshed and search text box's position Is changed during previous search operation. In some cases, After refreshing the page or javascript action, Position of element will remains same but still you will get this exception.

StaleObjectReference could be a real nightmare. I got the idea of StableWebElement - a wrapper which could detect Stale reference situation and try to find a new reference to the original element. All method for locating WebElement in my test always return StableWebElement wrapper and the problem with StaleObjectReferenceException disappeared.

The C# implementation is available on my project's page but I think it could be easily translated into java https://github.com/cezarypiatek/Tellurium/blob/master/Src/MvcPages/SeleniumUtils/StableWebElement.cs