1

I am trying to wait for an element on a page to be populated with inner text, which occurs after the page is refreshed. Obviously if the wait function checks the content of the element while the page is refreshing it will throw a stale element exception. I have enclosed this inside of a try/catch block to catch this exception and handle it but Visual Studio is still breaking and saying it is not handled.

Here is the code:

int attempts = 0;
while(attempts < 2) { 
    try
    {
        wait = new WebDriverWait(edgeDriver, TimeSpan.FromSeconds(30));
        wait.Until(d => d.FindElement(By.Id("lblFormatedIncidentID")).GetAttribute("innerText") != "");
        incidentId = edgeDriver.FindElement(By.Id("lblFormatedIncidentID")).GetAttribute("innerText");
        break;
    }
    catch (StaleElementReferenceException)
    {
        Debug.Print("Failed to acquire Incident ID - Stale element error. Retrying...");
        attempts++;
        if (attempts == 2)
        {
            throw;
        }

If I press continue in the debugger then it will catch the exception and handle it as expected. Does anyone know why this is happening and how to prevent it?

2
  • Can you try to actually add some more wait condition on try block . might be this would solve your problem Commented Nov 28, 2023 at 17:48
  • this would only loop for 1 second while stale... (polling loop in webdriver wait polls every 1/2 second) You might also check this solution: stackoverflow.com/questions/66820416/… Commented Nov 28, 2023 at 18:00

1 Answer 1

0

You can wait for value which you expected on page after reloading like:

string expectedText = "test";

try
{
   wait.Until(driver => 
   {
     try
     {
        string result = driver.FindElement(By.Id("lblFormatedIncidentID")).Text;

        return result.Contains(expectedText));
     }
     catch(WebDriverException ex) <-- this could be NoSuchElementException or StaleElementReferenceException
     {
        return false;
     }
   });
}
catch(WebDriverTimeoutException ex)
{
     throw ex;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.