java – stale element reference: element is not attached to the page document

java – stale element reference: element is not attached to the page document

What is the line which gives exception ??

The reason for this is because the element to which you have referred is removed from the DOM structure

I was facing the same problem while working with IEDriver. The reason was because javascript loaded the element one more time after i have referred so my date reference pointed to a nonexistent object even if it was right there in the UI. I used the following workaround:

try {
    WebElement date = driver.findElement(By.linkText(Utility.getSheetData(path, 7, 1, 2)));
    date.click();
}
catch(org.openqa.selenium.StaleElementReferenceException ex)
{
    WebElement date = driver.findElement(By.linkText(Utility.getSheetData(path, 7, 1, 2)));
    date.click();
}

See if the same can help you !

Whenever you face this issue, just define the web element once again above the line in which you are getting an Error.

Example:

WebElement button = driver.findElement(By.xpath(xpath));
button.click();

//here you do something like update or save 

//then you try to use the button WebElement again to click 
button.click();

Since the DOM has changed e.g. through the update action, you are receiving a StaleElementReference Error.

Solution:

WebElement button = driver.findElement(By.xpath(xpath));
button.click();

//here you do something like update or save 

//then you define the button element again before you use it
WebElement button1 = driver.findElement(By.xpath(xpath));
//that new element will point to the same element in the new DOM
button1.click();

java – stale element reference: element is not attached to the page document

This errors have two common causes: The element has been deleted entirely, or the element is no longer attached to the DOM.

If you already checked if it is not your case, you could be facing the same problem as me.

The element in the DOM is not found because your page is not entirely loaded when Selenium is searching for the element. To solve that, you can put an explicit wait condition that tells Selenium to wait until the element is available to be clicked on.

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, someid)))

See: https://selenium-python.readthedocs.io/waits.html

In Java

import org.openqa.selenium.support.ui.ExpectedConditions;

WebDriverWait wait = new WebDriverWait(driver, 10);
element = wait.until(ExpectedConditions.elementToBeClickable(By.id(someid)));

See: https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html

Leave a Reply

Your email address will not be published.