等待时发生 StaleElementReferenceException

StaleElementReferenceException while waiting

我的测试中有 wait 是这样的:

WebDriverWait wait = new WebDriverWait(dr, TimeSpan.FromSeconds(30));

...

wait.Until((d) =>
{
   if (d.FindElement(By.XPath("//*[@src='/loader.gif']")).Displayed)
   {
       System.Threading.Thread.Sleep(200);
       return false;
   }
   else
   {
       return true;
   }
});

我有时会 StaleElementReferenceException。它在 95% 的时间内都有效,但在测试中的不同地方都失败了。

错误:

Message: OpenQA.Selenium.StaleElementReferenceException : Element not found in the cache - perhaps the page has changed since it was looked up

我建议您尝试使用 ExpectedConditions,看看是否有帮助。

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
IWebElement loaderGif = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[@src='/loader.gif']")));