Stale Element Reference

I will provide the long answer, and a tl;dr. I think it’s helpful to understand what this exception means so that you can avoid it more generally in the future.

Long Answer

You may already be aware of what a StaleElementReferenceException is, but I will give some context anyway.

This error occurs when you attempt to use a reference to a WebElement that is no longer valid against the current DOM (i.e. the reference is “stale”). In other words, you have captured a WebElement, but at some point the page has changed in such a way that this element reference is no longer valid. This does not have to be an entire page reload or a redirect; It can happen even if only a portion of the page has changed in some way (after an AJAX request, for example). The randomness of this exception comes from the fact that page load times vary across iterations, so sometimes your script is able to use the element before it is reloaded, sometimes not.

This can be hard to visualize in the HTML itself. Imagine for a moment a very real scenario: You’ve located a link element. At some point, the element for your link is then removed from the DOM, then reloaded into the DOM as the exact same element. To you as the observer, this element doesn’t appear to have changed, but it’s technically not the same element, it’s a “copy”. If you located this link prior to it being removed/added back, then tried to use that reference after the reload, you would get the same exception. This is just one example among countless others.

Now, in reference to your exact custom keyword, I don’t have line numbers, but according to the error log its at dwKeywords.MakeModelCheck.verifyMakeModel(MakeModelCheck.groovy:80). If you can point me to exactly which line of code that is, I can give a specific answer as to what’s going on. However, I think you’d be better off following my advice below to handle this error more generally.

"Short" Answer

More generally, here’s what you can do to avoid StaleElementExceptions across the board. If you follow these simple principles, you will rarely ever see this exception in your future automation efforts:

1.) Ensure that EVERY element reference is 1-time use. In other words, locate the element, use it, and DO NOT use that same reference again. If you want to reference that element again, you should re-locate it in the HTML every single time.

2.) Ensure that you have proper wait conditions in place for every action you take in your application. Always wait for the page to be “static” prior to locating elements and using them.

I’m happy to elaborate, but this might be too much info already. Let me know :slight_smile:

2 Likes