wait.until(ExpectedConditions.visibilityOf Element1 OR Element2)

我想使用wait.until(ExpectedConditions)和TWO元素。 我正在运行测试,我需要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(); 

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

不幸的是,没有这样的命令。 您可以通过尝试捕获来克服这个问题,或者我建议您使用Watij 。

现在有一个本机解决方案, or方法, 检查文档 。

你这样使用它:

 driverWait.until(ExpectedConditions.or( ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.something")), ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.anything")))); 

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

 public static ExpectedCondition oneOfElementsLocatedVisible(By... args) { final List byes = Arrays.asList(args); return new ExpectedCondition() { @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; } }; } 

然后你可以这样使用它:

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

SERVICE_TITLE_LOCATORATTENTION_REQUEST_ALREADY_PRESENTS_WINDOW_LOCATOR是页面的两个静态定位器。

我认为如果你将“OR”放入xpath,你的问题有一个简单的解决方案。

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

然后,打印结果使用例如:

 if(driver.findElements(By.xpath("//h2[@class='....']")).size()>0){ driver.findElement(By.xpath("//h2[@class='....']")).getText(); }else{ driver.findElement(By.xpath("//h3[@class='....']")).getText(); } 

还有另一种方法可以等待,但它不是使用预期的条件而是使用lambda表达式代替..

 wait.Until(x => driver.FindElements(By.Xpath("//h3[@class='... ']")).Count > 0 || driver.FindElements(By.Xpath("//h2[@class='... ']")).Count > 0); 

你也可以像这样使用CSSSelector:

 wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("h2.someClass, h3.otherClass"))); 

将someClass和otherClass替换为xpath中[…]中的内容。

有一个简单的解决方案,使用显式等待:

 wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='FirstElement' or @id='SecondElement']"))); 

在此之前,我试图使用wait.until(ExpectedConditions.or(... ,它与2.53.0之前的selenium版本不兼容)。