C# Selenium StaleElementReferenceException当元素每秒刷新时
在我的web应用程序中,有一组每秒更新的进度条。当我在Chrome开发工具中查看DOM时,我可以看到元素正在被销毁和重新创建。因此,当我试图读取给定标签上的值或文本时,我得到一个StaleElementReferenceException 一个具体的例子是,我试图从这个元素的title属性中获取值。但在运行这行代码时,我一直会遇到错误C# Selenium StaleElementReferenceException当元素每秒刷新时,c#,selenium,selenium-webdriver,C#,Selenium,Selenium Webdriver,在我的web应用程序中,有一组每秒更新的进度条。当我在Chrome开发工具中查看DOM时,我可以看到元素正在被销毁和重新创建。因此,当我试图读取给定标签上的值或文本时,我得到一个StaleElementReferenceException 一个具体的例子是,我试图从这个元素的title属性中获取值。但在运行这行代码时,我一直会遇到错误 var progressBarCompletion = flyoutRow.JobProgressBar.GetAttribute("title"); 完整错
var progressBarCompletion = flyoutRow.JobProgressBar.GetAttribute("title");
完整错误消息:OpenQA.Selenium.StaleElementReferenceException:stale元素引用:元素未附加到页面文档如果没有HTML的完整上下文,编写一个完全工作的示例有点困难,但是我知道如何避免
StaleElementException
,并且仍然按照预期运行代码来检索title
我们可以尝试在循环中获取title
属性,在循环中我们try
/catch
获取StaleElementException
,希望仍然返回title
的值:
public string GetProgressBarTitle()
{
var currentAttempts = 0; // track number of attempts
// find the element for the first time
var progressBarCompletion = driver.Findlement(By.XPath("//div[contains(@class, 'progressJobProgressBar')]")); // this probably needs to be more specific to your row
// attempt to retrieve title, in a loop:
while (currentAttempts <= 5) // attempt to find the title up to 5 times
{
// try to get title...
try
{
var title = progressBarCompletion.GetAttribute("title");
return title;
}
catch (StaleElementReferenceException)
{
// if element is stale, find it again & retry
progressBarCompletion = driver.Findlement(By.XPath("//div[contains(@class, 'progressJobProgressBar')]"));
currentAttempts++; // increment number of attempts
}
} // end while
return string.Empty; // handle case where number of attempts passed & title was not returned
} // end method
它将抓取带有工作描述“Zipping”的进度条元素。这可能有点接近您要查找的内容。如果
弹出窗口
也是Web元素
,那么它也可能过时,而不仅仅是作业进度栏
。您最好自己尝试查找JobProgressBar
,而不是作为flyoutRow
的孩子。您是否也可以发布用于弹出式窗口.JobProgressBar
的代码?如果没有额外的代码上下文,很难准确地判断是什么引发了错误。html代码的屏幕截图是一种不好的做法,对于调试您的问题,没有人会为您编写它,这有助于帮助您自己。欢迎来到SO!请在下一篇博文中阅读并遵循相同的内容。请看这里的答案:我认为您可以在C#中构建类似的东西,并且您的StaleElementReferenceExceptions应该消失。我认为您可能打算将currentAttempts
初始化为0更正,谢谢。我最初使用的变量是maxtures
,但后来改为currentAttures
。
//li[div[text()='Zipping']]/div[contains(@class, 'progressJobProgressBar')]