Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 显式等待X元素可见_Java_Selenium_Selenium Webdriver - Fatal编程技术网

Java 显式等待X元素可见

Java 显式等待X元素可见,java,selenium,selenium-webdriver,Java,Selenium,Selenium Webdriver,我想等待一定数量的元素在页面上可见 为此,我使用: wait = new WebDriverWait(driver, timeout.getValueInSec()); wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(locator)); 虽然超时时间足够长,但这个方法返回的元素比我看到的和预期的要少(在这个具体的例子中是6个中的2个)。它可能会在找到2个元素后立即返回,而其他元素还没有出现 有没有办法告诉Sel

我想等待一定数量的元素在页面上可见

为此,我使用:

wait = new WebDriverWait(driver, timeout.getValueInSec());  
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(locator));
虽然超时时间足够长,但这个方法返回的元素比我看到的和预期的要少(在这个具体的例子中是6个中的2个)。它可能会在找到2个元素后立即返回,而其他元素还没有出现

有没有办法告诉Selenium驱动程序等待X元素? 比如:

wait.until(ExpectedConditions.visibilityOfNElementsLocatedBy(6, locator));

为您的特定需求定制并不困难:

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

我想这和我的例子一样有效。findElements()不等待,将返回当前显示的元素(在我的示例中是6个元素中的2个)。我需要一种方法来考虑X等待功能。关键是这
elements.size()!=ElementScont
检查(如果失败)是否会让selenium知道它需要继续调用条件,直到它不返回
null
。您是对的,它可以工作。我不明白那部分,显然有很多东西要学。:)谢谢
wait.until(visibilityOfNElementsLocatedBy(locator, 6));