【问题标题】:Debugging StaleElementReference exception - Selenium WebDriver调试 StaleElementReference 异常 - Selenium WebDriver
【发布时间】:2016-05-31 15:37:33
【问题描述】:

我在这里遇到了某种情况。

我有一个函数 editNewUser()。

public void editNewUser() throws Exception
    {
        driver.findElement(adminModuleDD).click();
        wait.until(ExpectedConditions.visibilityOfElementLocated(searchRes));
        List<WebElement> elements = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(uNames));
        for(WebElement el : elements)
        {
            if(el.getText().equals(UserName))
            {
                el.click();
                wait.until(ExpectedConditions.visibilityOfElementLocated(editUserHeading));
                driver.findElement(editUser).click();
                WebElement status_Dropdown = driver.findElement(By.xpath("//select[@id='systemUser_status']"));
                Select status = new Select(status_Dropdown);
                status.selectByVisibleText("Enabled");
            }
        }   
    }

UserName 是一个公共字符串变量,在创建用户期间在另一个函数中获取值。

在这个脚本中,我导航到一个包含用户列表的页面,我将所有用户名存储在列表“元素”中,然后遍历列表中文本与用户名匹配的每个元素。

现在,在我的 test_run 脚本中,我在 editNewUser() 之后调用了一些其他方法。

事情是这样的,这个方法在 if 块中执行以下命令。

if(el.getText().equals(UserName))
    {
        el.click();
        wait.until(ExpectedConditions.visibilityOfElementLocated(editUserHeading));
        driver.findElement(editUser).click();
        WebElement status_Dropdown = driver.findElement(By.xpath("//select[@id='systemUser_status']"));
        Select status = new Select(status_Dropdown);
        status.selectByVisibleText("Enabled");
    }

但是一旦调用 next 方法,它就会停止执行并抛出org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up

堆栈跟踪指的是if(el.getText().equals(UserName))这一行。

你能告诉我为什么我会收到这个异常,尽管执行了 if 块中的命令。

【问题讨论】:

  • 当 el.getText().equals(UserName) 条件为真时,您正在执行导航操作。因此,列表中的其余元素更改其位置或可能页面已更改,但在selenium 缓存作为异常发生..如果你正在实现这一点,如果条件为真,你应该打破循环..

标签: java selenium selenium-webdriver exception-handling staledataexception


【解决方案1】:

错误消息告诉您问题所在。一旦您在 for 循环中编辑了第一个“el”,页面就发生了变化,页面已经更新,因此 Selenium 已经失去了对“元素”列表中剩余元素的跟踪。

您需要找到另一种方法来跟踪您正在循环的元素。我过去使用的一种技术是创建一个自定义对象来表示项目,在您的情况下可能是“用户”。然后该对象就足够智能,可以在页面上重新找到自己。

【讨论】:

  • 你能给我一个小例子场景和它的工作原理吗?
  • 如果您的代码以面向对象的方式编写并使用页面对象模型,那将很简单。列出新用户的页面将有一个返回“用户”对象列表的方法。每个“用户”对象使用一些唯一的定位器识别用户对象,可能是一个 ID 号。 “用户”类也有一个方法来找到该用户的锚点……一个父 div 或将用户记录包装在页面中的东西。所有方法都首先查找该锚点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-03
相关资源
最近更新 更多