WebDriverManager setup failing to download chromedriver 116
这是复制该问题的代码。在 chromedriver 114 之前,这一切都工作正常,但当 chrome 浏览器升级到 116 时,它就崩溃了。
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class ChromeTest {
public static void main(String args[]) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
String title = driver.getTitle();
System.out.println(title);
driver.quit();
}
}
该错误表明库无法访问 116 的版本文件
del chromedriver.exe /s
以确保 ChromeDriver 的所有实例都从您的框中删除,以确保它不会从其他意外位置获取并使用它而不是下载 116。
- JeffC 2023-08-19
请使用最新版本的WebDriverManager。 WDM 版本 5.4.1 已经为我解决了这个问题。 Google 发布了新的 Chrome 风格,专门针对 Web 应用程序测试和自动化用例,这意味着 Chrome 驱动程序下载 URL 已从 Chrome 版本 115 更改
参考: https://developer.chrome.com/blog/chrome-for-testing/
WebDriver下载网址:https://googlechromelabs.github.io/chrome-for-testing/
我在 WebDriverManager 文档的 了解问题部分 中创建了一个新的小节(请参阅支持 chromedriver 115+)。
总而言之,解决此问题的方法是将 WebDriverManager 升级到最新版本(当前为 5.5.2)。另外,为了确保错误的版本没有缓存在resolution cache中(有关doc),您可以完全刷新缓存文件夹(至少一次),如下所示:
WebDriverManager.chromedriver().clearDriverCache().setup();
从4.6.0版本开始无需使用WebDriverManager,Selenium Manager会帮你直接下载并匹配浏览器驱动版本, 将你的 Selenium 升级到 4.11.0
对于 Mac 并使用 NPM webdriver-manager 包,
- 根据您的浏览器版本下载相同版本的 chrome-driver。 https://googlechromelabs.github.io/chrome-for-testing/
- 转到 cd
/usr/local/lib/node_modules/protractor/node_modules/webdriver-manager/selenium
。 - 将下载的 chrome-driver 复制到此文件夹。
- 使用最新的 selenium chrome 驱动程序版本重命名下载的 chrome-driver 版本。例如 -> 下载 chrome-driver 到 chromedriver_114.0.5735.90。
- 重命名后,也将其转换为zip文件夹。
- 从安全和隐私角度无论如何都允许。
现在,您将在最新的浏览器中使用最新的 selenium chrome 驱动程序。您不会看到以下错误“session not created: This version of ChromeDriver only supports Chrome version 114 Current browser version is 116.0.5845.110 with binary path /Applications/Google Chrome.app/Contents/MacOS/Google Chrome”。
重命名后不要运行 webdriver-manager update cmd,否则会覆盖旧版本的 chrome-driver
使用 Selenium Webdriver 版本 4.11.0 可以缓解此问题
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.11.0</version>
</dependency>
// WebDriverManager.chromedriver().setup(); -- Not required
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.*;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Selenium {
private static WebDriver driver = null;
private static final String CHROMEDRIVER_VERSION_FILE = "chromedriver_version.txt";
private static final String userHome = System.getProperty("user.home");
private static final String baseChromeDriverPath = userHome + "\\.cache\\selenium\\chromedriver\\";
static {
checkAndCreateVersionFile();
}
public static void checkAndCreateVersionFile() {
File file = new File(CHROMEDRIVER_VERSION_FILE);
if (!file.exists()) {
try {
if (file.createNewFile()) {
saveChromeDriverVersion("Ваша версия ChromeDriver");
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Ошибка при создании файла chromedriver_version.txt: " + e.getMessage());
}
}
}
public static WebDriver getDriver() {
return driver;
}
public static void setDriver(WebDriver driver) {
Selenium.driver = driver;
}
public static void saveChromeDriverVersion(String version) {
try (FileWriter writer = new FileWriter(CHROMEDRIVER_VERSION_FILE)) {
writer.write(version);
} catch (IOException e) {
System.out.println("Error saving ChromeDriver version: " + e.getMessage());
}
}
public static String getSavedChromeDriverVersion() {
try (BufferedReader reader = new BufferedReader(new FileReader(CHROMEDRIVER_VERSION_FILE))) {
return reader.readLine().trim();
} catch (IOException e) {
System.out.println("Error reading saved ChromeDriver version: " + e.getMessage());
return null;
}
}
private static final String CHROME_FOR_TESTING_URL = "https://googlechromelabs.github.io/chrome-for-testing/";
public static String getChromeDriverDownloadLink(String majorVersion) throws Exception {
Document doc = Jsoup.connect(CHROME_FOR_TESTING_URL).get();
Elements rows = doc.select("tr.status-ok");
for (org.jsoup.nodes.Element row : rows) {
if (row.select("th code:containsOwn(win64)").size() > 0) {
String downloadLink = row.select("td code").first().text();
if (downloadLink.contains("chromedriver") && downloadLink.contains(majorVersion)) {
return downloadLink;
}
}
}
throw new Exception("Download link not found for Chrome major version: " + majorVersion);
}
public static String getChromeDriverVersion() {
try {
return WebDriverManager.chromedriver().getDownloadedDriverVersion();
} catch (Exception e) {
System.out.println("Error getting ChromeDriver version: " + e.getMessage());
return null;
}
}
public static String extractVersionFromDownloadLink(String downloadLink) {
// Предполагается, что ссылка имеет формат подобный .../chromedriver/{version}/chromedriver_win32.zip
String[] parts = downloadLink.split("/");
return parts[parts.length - 3];
}
public static WebDriver startDriver(boolean hidden) throws Exception {
String majorVersion = getChromeVersion().split("\\.")[0];
String downloadLink = getChromeDriverDownloadLink(majorVersion);
String currentChromeDriverVersion = extractVersionFromDownloadLink(downloadLink);
String savedChromeDriverVersion = getSavedChromeDriverVersion();
String arch = downloadLink.contains("win64") ? "win64" : "win32";
String PathCurrentDriver = baseChromeDriverPath + arch + "\\" + currentChromeDriverVersion + "\\chromedriver.exe";
if (currentChromeDriverVersion.equals(savedChromeDriverVersion) && fileExists(PathCurrentDriver)){
// Если драйвер найден, копируем его
Main.uniquePath = baseChromeDriverPath + arch + "\\" + currentChromeDriverVersion + "\\" + "chromedriver_" + System.currentTimeMillis() + ".exe";
Files.copy(Paths.get(PathCurrentDriver), Paths.get(Main.uniquePath));
// Используем путь к уникальному драйверу
System.setProperty("webdriver.chrome.driver", Main.uniquePath);
}else{
if (currentChromeDriverVersion == null) {
System.out.println("Chrome is not found on your system");
return null;
}
String[] architectures = { "win32", "win64" };
boolean driverExists = false;
for (String archi : architectures) {
String chromeDriverPath = baseChromeDriverPath + archi + "\\" + currentChromeDriverVersion + "\\chromedriver.exe";
if (Files.exists(Paths.get(chromeDriverPath))) {
driverExists = true;
System.setProperty("webdriver.chrome.driver", chromeDriverPath);
break;
}
}
if (!driverExists) {
try { downloadAndSetupDriver(downloadLink, currentChromeDriverVersion);
} catch (Exception e) {
WebDriverManager.chromedriver().forceDownload().setup();
e.printStackTrace();
return null;
}
}else {
// Если драйвер найден, копируем его
Main.uniquePath = baseChromeDriverPath + arch + "\\" + currentChromeDriverVersion + "\\" + "chromedriver_" + System.currentTimeMillis() + ".exe";
Files.copy(Paths.get(baseChromeDriverPath + arch + "\\" + currentChromeDriverVersion + "\\chromedriver.exe"), Paths.get(Main.uniquePath));
// Используем путь к уникальному драйверу
System.setProperty("webdriver.chrome.driver", Main.uniquePath);
}
}
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--disable-gpu", "--window-size=1800,1000", "--ignore-certificate-errors", "--no-sandbox");
if (hidden) {
//chromeOptions.addArguments("--headless");
}
try {
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().deleteAllCookies();
driver.manage().window().setPosition(new Point(0, 0));
setDriver(driver);
return driver;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void downloadAndSetupDriver(String downloadLink, String currentChromeDriverVersion) throws IOException {
// Определение архитектуры скачанного файла
String arch = downloadLink.contains("win64") ? "win64" : "win32";
// Скачивание ChromeDriver
String driverVersion = extractVersionFromDownloadLink(downloadLink);
saveChromeDriverVersion(driverVersion);
String zipFilePath = baseChromeDriverPath + "chromedriver.zip";
downloadFile(downloadLink, zipFilePath);
// Распаковка и копирование
String destDir = baseChromeDriverPath + arch + "\\" + currentChromeDriverVersion;
Unzip.zipExtractor(zipFilePath, destDir);
Files.copy(Path.of(Paths.get(destDir) + "\\chromedriver.exe"), Paths.get(baseChromeDriverPath + arch + "\\" + currentChromeDriverVersion + "\\" + Main.uniquePath));
System.setProperty("webdriver.chrome.driver", baseChromeDriverPath + arch + "\\" + currentChromeDriverVersion + "\\" + Main.uniquePath);
}
public static String getChromeVersion() {
String os = System.getProperty("os.name").toLowerCase();
String[] cmd;
if (os.contains("win")) {
cmd = new String[]{"powershell", "(Get-Item 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe').VersionInfo.ProductVersion"};
} else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
cmd = new String[]{"/bin/bash", "-c", "google-chrome --version"};
} else {
throw new UnsupportedOperationException("Unsupported operating system: " + os);
}
ProcessBuilder processBuilder = new ProcessBuilder(cmd);
try {
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String version = reader.readLine();
if (version != null) {
return version.trim();
}
} catch (IOException e) {
System.out.println("Exception while getting Chrome version: " + e);
}
System.out.println("Chrome version not found");
return null;
}
public static void downloadFile(String url, String localFilename) throws IOException {
try (ReadableByteChannel rbc = Channels.newChannel(new URL(url).openStream());
FileOutputStream fos = new FileOutputStream(localFilename)) {
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
}
public static void quitDriver() {
if (driver != null) {
driver.quit();
}
try {
Files.deleteIfExists(Paths.get(Main.uniquePath));
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean fileExists(String path) {
File file = new File(path);
return file.exists();
}
}