Dealing with StaleElementReferenceException error

43 views
Skip to first unread message

Faisal Dama

unread,
Jan 10, 2023, 1:49:47 AM1/10/23
to Selenium Users

Hi,

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.

EditCustomerPage.java This is the page object file  Error is on Line 34.

EditCustomer   This is the test

Stack Trace


Thanks. 

Dall E

unread,
Jan 11, 2023, 10:24:42 PM1/11/23
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(By.id("someid"))));

or

Copy code
WebElement element = driver.findElement(By.id("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

unread,
Jan 18, 2023, 3:17:13 PM1/18/23
to Selenium Users
Remove the cache lookup

Adrian

unread,
Jan 18, 2023, 4:16:58 PM1/18/23
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()

Cheers,
Adrian.

Reply all
Reply to author
Forward
0 new messages