wait.until(ExpectedConditions.visibilityOf Element1 OR Element2)

8 java selenium

我希望使用wait.until(ExpectedConditions)两个元素.我正在运行测试,我需要WebDriver等到Element1或Element2中的任何一个出现.然后我需要选择先出现的人.我试过了:

WebDriverWait wait = new WebDriverWait(driver, 60); 
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h2[@class='....']"))) || wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h3[@class='... ']"))); 

        // Then I would need:

String result = driver.findElement(By.xpath("...")).getText() || driver.findElement(By.xpath("...")).getText();
Run Code Online (Sandbox Code Playgroud)

总而言之,我需要等到两个元素中的任何一个出现.然后挑选出现的人(他们不能同时出现)请帮助.

dia*_*lex 16

现在有一个原生的解决方案,or方法,检查文档.

你这样使用它:

driverWait.until(ExpectedConditions.or(
    ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.something")),
    ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.anything"))));
Run Code Online (Sandbox Code Playgroud)

  • 我如何确保条件属于哪个元素? (2认同)

小智 7

这是我在Helper类中声明的方法,它就像一个魅力.只需创建自己的,ExpectedCondition并使其返回定位器找到的任何元素:

public static ExpectedCondition<WebElement> oneOfElementsLocatedVisible(By... args)
{
    final List<By> byes = Arrays.asList(args);
    return new ExpectedCondition<WebElement>()
    {
        @Override
        public Boolean apply(WebDriver driver)
        {
            for (By by : byes)
            {
                WebElement el;
                try {el = driver.findElement(by);} catch (Exception r) {continue;}
                if (el.isDisplayed()) return el;
            }
            return false;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样使用它:

Wait wait = new WebDriverWait(driver, Timeouts.WAIT_FOR_PAGE_TO_LOAD_TIMEOUT);
WebElement webElement = (WebElement) wait.until(
        Helper.oneOfElementsLocatedVisible(
                By.xpath(SERVICE_TITLE_LOCATOR), 
                By.xpath(ATTENTION_REQUEST_ALREADY_PRESENTS_WINDOW_LOCATOR)
        )
);
Run Code Online (Sandbox Code Playgroud)

这里SERVICE_TITLE_LOCATOR和ATTENTION_REQUEST_ALREADY_PRESENTS_WINDOW_LOCATOR是页面两个静态定位器.


CHE*_*HKA 0

不幸的是,没有这样的命令。你可以通过 try 和 catch 来克服这个问题,或者我最好推荐你使用开源 Ruby 库Watir。