如何使用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,但它正是我想要评估的。有任何想法吗?
答案 0 :(得分:30)
以下内容可能有助于您的要求。 在下面的代码中,我们覆盖了包含我们正在寻找的条件的apply方法。因此,只要条件不为真,在我们的情况下,启用不是真的,我们进入循环最多10秒,每500毫秒轮询一次(这是默认值),直到apply方法返回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;
}
});
答案 1 :(得分:1)
如果有人想在Selenium包装器中使用@Sri作为方法,可以采用以下方法(感谢this answer btw):
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));
}
答案 2 :(得分:0)
当对一个非常慢的引导页面进行自动化,等待排序按钮生效时,这对我有用。
new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.attributeContains(BUTTON_SORT_ASCENDING_PRICE, "class", "sortButtonActive"));
Selenium V3.01
答案 3 :(得分:0)
也可以使用简单的do-while循环System.currentTimeMillis();方法可用于避免无限循环
long startTime = System.currentTimeMillis();
String disabled;
do{
disabled = element.getAttribute("attributeName").trim();
}while(disabled!="false" && System.currentTimeMillis()-startTime<10000);
答案 4 :(得分:0)
您可以使用xpath定义具有所需值属性的元素,然后等待它出现在页面上。 在Python中,它可能看起来像这样:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
xp = '//*[@id="element_id"][@aria-disabled="false"]'
WebDriverWait(browser, 60).until(EC.presence_of_element_located((By.XPATH, xp)))