How to Avoid "Staleelementreferenceexception" in Selenium

How to avoid StaleElementReferenceException in Selenium?

This can happen if a DOM operation happening on the page is temporarily causing the element to be inaccessible. To allow for those cases, you can try to access the element several times in a loop before finally throwing an exception.

Try this excellent solution from darrelgrainger.blogspot.com:

public boolean retryingFindClick(By by) {
boolean result = false;
int attempts = 0;
while(attempts < 2) {
try {
driver.findElement(by).click();
result = true;
break;
} catch(StaleElementException e) {
}
attempts++;
}
return result;
}

Selenium: How to avoid StaleElementReferenceException when looping through a set of elements?

Well after tearing my hair out for a day, I finally realized what was happening. It should have been obvious to me. When the "Next" button is clicked, it takes some time for the new page to load. By simply adding a delay, the new DOM is loaded and processing begins on it, not again on the previous one!

            driver.findElement(By.xpath(".//*[@class='PageRight']")).click();
try {
Thread.sleep(4000); //provide some time for the page to load before processing it
} catch (InterruptedException ex) {
Logger.getLogger(RealAuction.class.getName()).log(Level.SEVERE, null, ex);
}

Now it runs to completion with no StaleElementReferenceException.

Getting error - org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

Stale element exception means element is there on web page but selenium could not interct that element , there are 2 ways to resolve that
1.Try with page refresh(driver.navigate().refresh();)
2.Just use loop element until click that element

Python & Selenium: How to avoid StaleElementReferenceException error from dividend.com

StaleElementReferenceException means selected element may no longer in html dom.However,there are plenty of reasons behind this exception like incorrect element selection,load time and so on. So You need to use webdriverwait.

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

from selenium.webdriver.chrome.options import Options

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

option = webdriver.ChromeOptions()
option.add_argument("start-maximized")

#chrome to stay open
option.add_experimental_option("detach", True)

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),options=option)
driver.get('https://www.dividend.com/dividend-champions/')

names = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, '//*[@class="mp-table-body"]/div[@class="mp-table-body-row-container mp-table-row t-static"]')))

for name in names:
company = name.find_element(By.XPATH,'.//a[@class="m-table-body-link-text m-table-stocks-name-col m-table-long-name"]').text
print(company)

Output:

Eversource Energy
Andersons Inc.
J.M. Smucker Co.
Cambridge Bancorp
Factset Research Systems Inc.
Graco Inc.
First Of Long Island Corp.
Stepan Co.
MDU Resources Group Inc
W. P. Carey Inc
Church & Dwight Co., Inc.
Lincoln Electric Holdings, Inc.
Matthews International Corp. - Ordinary Shares - Class A
New Jersey Resources Corporation
Bank OZK
Caterpillar Inc.
Brown & Brown, Inc.
Carrier Global Corp
Polaris Inc
International Business Machines Corp.
NextEra Energy Inc
Realty Income Corp.
RenaissanceRe Holdings Ltd
Cullen Frost Bankers Inc.
Otis Worldwide Corp
Roper Technologies Inc
West Pharmaceutical Services, Inc.
Bancfirst Corp.
Albemarle Corp.
Aptargroup Inc.

WebdriverManager

How to avoid StaleElementReferenceException error in python selenium

Slight change of approach. Collect all links first, then process them as you wish.

url = 'http://www.mosquedirectory.co.uk/browse/uk/england/london'

browser = webdriver.Chrome()
browser.get(url)

listings = WebDriverWait(browser, 30).until(EC.presence_of_all_elements_located((By.XPATH, "//div[@id='directory_listingBrowse']//ul//*//a[@href]")))

all_links = [listing.get_attribute('href') for listing in listings]

for link in all_links:
browser.get(link)
#do whatever else here

Don't forget to add these imports:

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

Selenium WebDriver StaleElementReferenceException

I ran across this same problem and could not find any solutions. Came up with a solution and posting it here, hope this helps someone with the same problem. I created a class to handle stale elements depending on their type, cssselector, id, etc and simply call it like I would any other page object.

public void StaleElementHandleByID (String elementID)
{
int count = 0;
boolean clicked = false;
while (count < 4 && !clicked)
{
try
{
WebElement yourSlipperyElement= driver.findElement(By.id(elementID));
yourSlipperyElement.click();
clicked = true;
}
catch (StaleElementReferenceException e)
{
e.toString();
System.out.println("Trying to recover from a stale element :" + e.getMessage());
count = count+1;
}
}
}

I'd recommend only using this on elements you know cause problems for WebDriver.



Related Topics



Leave a reply



Submit