WebDriverWait 等待元素属性改变 [英] WebDriverWait for an element attribute to change

查看:40
本文介绍了WebDriverWait 等待元素属性改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I use WebDriverWait to wait until an attribute changes?

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

In my AUT I have to wait for a button to become enabled before continuing, unfortunately due to the way the developer coded the page I can't use WebElement's isEnabled() method. The developer is using some CSS to just make the button look like it's disabled so the user can't click on it and the method isEnabled always returns true for me. So what I have to do is get the attribute "aria-disabled" and check whether the text is "true" or "false". What I've been doing so far is a for loop with Thread.sleep, something like this:

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);
 }

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

(disregard the code above if incorrect, just pseudo code of what I'm doing)

我确信有一种方法可以使用 WebDriverWait 实现类似的目标,这是我无法弄清楚的首选方法.这就是我想要实现的目标,即使以下方法不起作用:

I'm sure there's a way to achieve something similar using WebDriverWait which is the preferred method I just can't figure out how. This is what I'm trying to achieve even though the following won't work:

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

显然它不起作用,因为该函数需要一个 WebElement 而不是字符串,但这是我想要评估的.有任何想法吗?

Obviously it doesn't work because the function is expecting a WebElement not String but it's what I'm trying to evaluate. Any ideas?

推荐答案

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

The following might help your requirement. In the following code, we override apply method incorporating the condition that we are looking for. So, as long as the condition is not true, in our case, the enabled is not true, we go in a loop for a maximum of 10 seconds, polling every 500 ms (this is the default) until the apply method returns true.

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;
    }
});

这篇关于WebDriverWait 等待元素属性改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆