Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

selenium - WebDriverWait for an element attribute to change

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

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)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...