我想等待一定数量的元素在页面上可见。
为此,我使用:
wait = new WebDriverWait(driver, timeout.getValueInSec());
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(locator));
虽然超时时间足够长,但此方法返回的元素比我看到和预期的要少(在本具体示例中为 6 个中的 2 个)。它可能会在找到 2 个元素后立即返回,然后其他元素才出现。
有没有办法告诉 Selenium 驱动程序等待 X 元素? 像这样的东西:
wait.until(ExpectedConditions.visibilityOfNElementsLocatedBy(6, locator));
最佳答案
定制并不难 Expected Condition 满足您的具体要求:
public static ExpectedCondition<List<WebElement>> visibilityOfNElementsLocatedBy(
final By locator, final int elementsCount) {
return new ExpectedCondition<List<WebElement>>() {
@Override
public List<WebElement> apply(WebDriver driver) {
List<WebElement> elements = findElements(locator, driver);
// KEY is here - we are "failing" the expected condition
// if there are less than elementsCount elements
if (elements.size() < elementsCount) {
return null;
}
for(WebElement element : elements){
if(!element.isDisplayed()){
return null;
}
}
return elements;
}
@Override
public String toString() {
return "visibility of N elements located by " + locator;
}
};
}
用法:
wait.until(visibilityOfNElementsLocatedBy(locator, 6));
关于java - 显式等待 X 元素可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30508334/