Created
June 26, 2023 08:04
-
-
Save python012/c7a2b48d2f58d54394a795953f76f3c2 to your computer and use it in GitHub Desktop.
使用Java 8中提供的CompletableFuture来实现异步等待多个Web元素的功能。下面是一个可能的解决方案
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.openqa.selenium.By; | |
import org.openqa.selenium.WebDriver; | |
import org.openqa.selenium.WebElement; | |
import org.openqa.selenium.chrome.ChromeDriver; | |
import org.openqa.selenium.support.ui.ExpectedConditions; | |
import org.openqa.selenium.support.ui.WebDriverWait; | |
import java.util.concurrent.CompletableFuture; | |
import java.util.concurrent.ExecutionException; | |
public class WaitForMultipleElementsAsync { | |
public static void main(String[] args) throws ExecutionException, InterruptedException { | |
WebDriver driver = new ChromeDriver(); | |
driver.get("https://www.example.com"); | |
// 创建两个CompletableFuture对象 | |
CompletableFuture<WebElement> elem1Future = CompletableFuture.supplyAsync(() -> waitForElement(driver, By.cssSelector("#elem1"))); | |
CompletableFuture<WebElement> elem2Future = CompletableFuture.supplyAsync(() -> waitForElement(driver, By.cssSelector("#elem2"))); | |
// 等待任意一个元素被找到 | |
CompletableFuture.anyOf(elem1Future, elem2Future).join(); | |
// 如果elem1被找到,则取消elem2的执行 | |
if (elem1Future.isDone() && !elem2Future.isDone()) { | |
elem2Future.cancel(true); | |
System.out.println("elem1 found"); | |
} | |
// 如果elem2被找到,则取消elem1的执行 | |
if (elem2Future.isDone() && !elem1Future.isDone()) { | |
elem1Future.cancel(true); | |
System.out.println("elem2 found"); | |
} | |
// 继续执行您的代码 | |
System.out.println("next step"); | |
// 关闭浏览器 | |
driver.quit(); | |
} | |
private static WebElement waitForElement(WebDriver driver, By locator) { | |
WebDriverWait wait = new WebDriverWait(driver, 10); | |
return wait.until(ExpectedConditions.presenceOfElementLocated(locator)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment