Selenium - stale element reference: element is not attached to the page

Viewed 54893

I am trying to understand why it gives an error while I am trying to display items that took from websites. I am also using google chrome for a browser.

chromeDriver.Navigate().GoToUrl("somewebsites");

chromeDriver.FindElement(By.Id("something.link.text")).Click();
chromeDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));

And this other parts of my code

var item = chromeDriver.FindElementsByXPath("//*[starts-with(@id,\"g_1_\")]/td[3]/span");
foreach (var value in item)
{
    Console.WriteLine(value.Text); 
}

Whenever I use "chromeDriver.FindElement(By.Id("something.link.text")).Click();", it gives an error. I can't display the data that I pulled.

In the error message, It says "OpenQA.Selenium.StaleElementReferenceException: 'stale element reference: element is not attached to the page document". I checked the other posts, but I did not figure it out. How can I solve it?

As I read, selenium gives much faster response than website opening time, so it gives the error. Also, rarely, it gives that selenium cannot be located the element. Any suggestion?

EDIT: If I remove ".text" from display function, It displays "OpenQA.Selenium.Remote.RemoteWebElement". Does the problems with strings ?

EDIT2: I can hold data that I took from websites as like this:

[i]="System.Collections.ObjectModel.ReadOnlyCollection`1[OpenQA.Selenium.IWebElement]" For this, I wrote something like this:

string[] test= new string[100];

for (int i = 0; i < 100; i++)
{
     kaan[i] = driver.FindElements(By.XPath("//*[starts-with(@id,\"g_1_\")]/td[3]/span")).ToString();
}

How can I convert to the text

5 Answers

I have been to a similar situation.Here the main problem is page needs time so I added time.sleep(sec) and it worked fine.

A solution that worked for me was using recursion to create a fresh webelement after the page has been refreshed. This idea was mentioned by santhosh kumar in this thread. This is the code snippet.

def preventStaleElement(Bool):
    while(Bool):
        # During the recursion, a new element will be created since the try 
        # block is run once more
        try:
            element = driver.find_element(By.CLASS_NAME, "mouseover_load")
            action = ActionChains(driver).move_to_element(element)
            action.perform()
        except StalElementReferenceException:
            preventStaleElement(True)



   
Related