新版本需要增加以下配置(我使用的是 4.23.0 版本)
// 创建 ChromeOptions 实例
ChromeOptions options = new ChromeOptions();
// 设置性能日志级别为 ALL
options.setCapability("goog:loggingPrefs", ImmutableMap.of("performance", "ALL"));
WebDriver driver = new ChromeDriver(options);
伪代码
/**
* 等待接口执行完成
* @param path 接口路径
*/
private static void waiteApi(WebDriver driver, String path) {
// 定义一个预期条件来等待 AJAX 请求完成
// 使用 WebDriverWait 等待 AJAX 请求完成
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); // 最长等待时间为 10 秒
wait.until(webDriver -> {
LogEntries performanceLogs = webDriver.manage().logs().get(LogType.PERFORMANCE);
List<LogEntry> entries = performanceLogs.getAll();
for (LogEntry entry : entries) {
String message = entry.getMessage();
if (message.contains("Network.responseReceived") && message.contains(path)) { // 假设接口路径为 /api/some-endpoint
return true;
}
}
return false;
});
// 在这里执行其他操作
System.out.println("AJAX request has completed.");
}
public static void main(String[] args) {
// 创建 ChromeOptions 实例
ChromeOptions options = new ChromeOptions();
// 设置性能日志级别为 ALL
options.setCapability("goog:loggingPrefs", ImmutableMap.of("performance", "ALL"));
WebDriver driver = new ChromeDriver(options);
WebElement loginButton = driver.findElement(By.className("login-button"));
//登录
loginButton.click();
waiteApi(driver, "user/login");
}