WebDriver等待元素属性改变

新手上路,请多包涵

如何使用 WebDriverWait 等待属性更改?

在我的 AUT 中,我必须等待按钮启用才能继续,不幸的是,由于开发人员对页面进行编码的方式,我无法使用 WebElement 的 isEnabled() 方法。开发人员正在使用一些 CSS 来使按钮看起来像是被禁用,因此用户无法单击它并且方法 isEnabled 总是为我返回 true。所以我要做的是获取属性“aria-disabled”并检查文本是“true”还是“false”。到目前为止,我一直在做的是使用 Thread.sleep 的 for 循环,如下所示:

 for(int i=0; i<6; ++i){
    WebElement button = driver.findElement(By.xpath("xpath"));
    String enabled = button.getText()
    if(enabled.equals("true")){ break; }
    Thread.sleep(10000);
 }

(如果不正确请忽略上面的代码,只是我正在做的伪代码)

我确信有一种方法可以使用 WebDriverWait 实现类似的效果,这是我不知道如何实现的首选方法。这就是我想要实现的目标,即使以下方法不起作用:

 WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOf(refresh.getText() == "true"));

显然它不起作用,因为该函数期望 WebElement 而不是 String,但这是我要评估的内容。有任何想法吗?

原文由 so cal cheesehead 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 617
2 个回答

以下内容可能对您的要求有所帮助。在下面的代码中,我们覆盖了包含我们正在寻找的条件的 apply 方法。因此,只要条件不为真,在我们的例子中,enabled 不为真,我们将进入一个最多 10 秒的循环,每 500 毫秒轮询一次(这是默认设置),直到 apply 方法返回真。

 WebDriverWait wait = new WebDriverWait(driver,10);

wait.until(new ExpectedCondition<Boolean>() {
    public Boolean apply(WebDriver driver) {
        WebElement button = driver.findElement(By.xpath("xpath"));
        String enabled = button.getAttribute("aria-disabled");
        if(enabled.equals("true"))
            return true;
        else
            return false;
    }
});

原文由 Sridevi Yedidha 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果有人想在 Selenium 包装器中使用 @Sri 作为方法,这里有一种方法可以做到(顺便说一句,感谢 这个答案):

 public void waitForAttributeChanged(By locator, String attr, String initialValue) {
    WebDriverWait wait = new WebDriverWait(this.driver, 5);

    wait.until(new ExpectedCondition<Boolean>() {
        private By locator;
        private String attr;
        private String initialValue;

        private ExpectedCondition<Boolean> init( By locator, String attr, String initialValue ) {
            this.locator = locator;
            this.attr = attr;
            this.initialValue = initialValue;
            return this;
        }

        public Boolean apply(WebDriver driver) {
            WebElement button = driver.findElement(this.locator);
            String enabled = button.getAttribute(this.attr);
            if(enabled.equals(this.initialValue))
                return false;
            else
                return true;
        }
    }.init(locator, attr, initialValue));
}

原文由 Arthur 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题