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();
}
}
del chromedriver.exe /s
from c:\ command prompt to make sure that all instances of ChromeDriver are removed from your box to make sure it's not picking it up from some other unexpected location and using that instead of downloading 116. – Bondswoman