As described here and in many other tutorials and questions describing the StaleElementReferenceException
by Driver.FindElementsByCssSelector(".simple-grid .sg-row>.sg-cell")
command you actually catching the web element matching the passed locator and storing a reference to it in IWebElement FirstCell
.
But since the web page is still dynamically changing, not yet finally built, a moment after that the reference you stored becomes stale, old, invalid since the web element was changed.
This is why by involving the FirstCell.Click()
inside the try
block you are getting the StaleElementReferenceException
.
Trying to involve the absolutely same action inside the catch
block will throw StaleElementReferenceException
again since you still using the already known as invalid (stale) FirstCell
reference.
What you can do to make your code work is to get that element reference Again inside the catch block and try click it.
Like this:
IWebElement FirstCell => Driver.FindElementsByCssSelector(".simple-grid .sg-row>.sg-cell").FirstOrDefault();
void Test()
{
try
{
FirstCell.Click();
}
catch (StaleElementReferenceException)
{
FirstCell = Driver.FindElementsByCssSelector(".simple-grid .sg-row>.sg-cell").FirstOrDefault();
FirstCell.Click(); //retry - Now this indeed should find element again and return new instance
}
}
However this will also not surely work since possibly the page is still not fully, finally stable.
To make this work you can do this in a loop, something like this:
void Test()
{
IWebElement FirstCell;
for(int i=0;i<10;i++){
try
{
FirstCell = Driver.FindElementsByCssSelector(".simple-grid .sg-row>.sg-cell").FirstOrDefault();
FirstCell.Click();
}
catch (StaleElementReferenceException)
{
System.Threading.Thread.Sleep(200);
}
}
}