如何避免Selenium中的StaleElementReferenceException?

时间:2018-01-13 04:09:57

标签: c# selenium exception exception-handling

我到处寻找并看到了许多解决方案但不幸的是,在我的情况下,这不是等待元素可见性的问题。

基本上我正在分析一个网页,其内容在某些内部更新,因此网页的数量会发生变化。但我查询的元素数量是不变的。总共10个元素。我一直在查询这些元素但很快我得到“StaleElementReferenceException”,因为我假设在调用FindElement或FindElements并且我访问.Text属性时,该项目是陈旧的。

我也试过Try / Catch,但没有运气。我不在乎这个元素是否陈旧,下次我会得到它,因为我一直在阅读它们。

如何解决此问题?

3 个答案:

答案 0 :(得分:0)

陈旧元素异常 - 告诉您页面已更改,但您的网页元素实例未更改。这意味着当您的页面的HTML代码发生变化时,您应该再次找到该元素,因为html已更改。这就是硒的作用方式。

答案 1 :(得分:0)

抓住异常对我有用。只需在catch块中再次找到该元素即可。 这个例子是用Java编写的,但我确定你已经有了这个想法:

    public boolean isElementContentUpdated() {
    boolean isContentUpdated = false;

    try {
        isContentUpdated = checkElementContentIsUpdated(elementToCheck);
    } catch (StaleElementReferenceException e) {
        elementToCheck = waitForElement(getDriver().findElement(By));
        isContentUpdated = checkElementContentIsUpdated(elementToCheck);
    }

    return isContentUpdated ;
}

当然你必须实现你的方法checkElementIsUpdated(elementToCheck)

答案 2 :(得分:0)

如果您正在使用PageObjects,请在每个时间间隔创建新实例,以便再次初始化元素,然后驱动程序重新读取dom。

E.g。

//Your page object get initialized along with it's elements
AccountPage accountPage = new AccountPage(); 

//Do stuff

//Interval passed, recreate the page to get new elements
accountPage = new AccountPage();