Dealing with StaleElementReferenceException error

Skip to first unread message

Faisal Dama

Jan 10, 2023, 1:49:47 AMJan 10
to Selenium Users


I am new to Selenium and I am getting a StaleElementReferenceException error but not sure why. I have tried to debug to no avail. It would be great if someone could point me to the issue. I have posted below links to the code on Gist and the stack trace as well. This is the page object file  Error is on Line 34.

EditCustomer   This is the test

Stack Trace


Dall E

Jan 11, 2023, 10:24:42 PMJan 11
to Selenium Users

A StaleElementReferenceException is a specific type of exception that is thrown when a web driver is trying to interact with a web page element that is no longer present in the DOM (Document Object Model). 

This can happen when the page is refreshed, or when an element on the page is replaced with a new element, for example, as a result of an AJAX request.

This error usually means that the element you are trying to interact with no longer exist. You should try to find the element again.

This can occur in Selenium webdriver (Java), where one common cause of this error occurs when the element is located after a page refresh or navigation, thus you will need to handle the wait and find the 

element again using the updated DOM.

You can handle this exception by using the following

Copy code
try{ //Code that causes the exception }catch(StaleElementReferenceException e){ //Code to handle the exception }

You could try

Copy code
WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.refreshed(ExpectedConditions.elementToBeClickable("someid"))));


Copy code
WebElement element = driver.findElement("someid")); ((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);

It's also worth noting that this exception could also be thrown by other ways like when navigating to different pages on your application and then trying to interact with elements on the previous page.

anwesana kanungo

Jan 18, 2023, 3:17:13 PMJan 18
to Selenium Users
Remove the cache lookup


Jan 18, 2023, 4:16:58 PMJan 18
to Selenium Users
Hi Faisal,
I think the problem is the caused by the line before where you dismiss the alert dialog.
I could be wrong, but I think the switchTo() command is changing the scoping from your page to the alert dialog.
So the next line is trying to send keys to the Customer Id input field, but it is trying to find the field on the alert dialog - which no longer exists.
Try switching back to the page or don't switch to the alert dialog in the first place.
I think the command for that is driver.switchTo().defaultContent()


Reply all
Reply to author
0 new messages