我想等待页面上显示一定数量的元素。
为此,我使用:
wait = new WebDriverWait(driver, timeout.getValueInSec());
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(locator));
尽管超时足够长,但此方法返回的元素少于我看到和期望的元素(在这个具体情况下为6个中的2个)。它可能会在找到2个元素之后立即返回,然后其余元素就会返回。
有没有办法告诉Selenium驱动程序等待X元素? 类似的东西:
wait.until(ExpectedConditions.visibilityOfNElementsLocatedBy(6, locator));
答案 0 :(得分:1)
为您的特定要求制作自定义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));