4

Here is the code to replicate the issue. This was working fine till chromedriver 114 but it broke as soon as chrome browser got upgraded to 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();
  }
}

The error shows that the Library is unable access the version file for 116

Amit
  • 182
  • 3
  • 3
  • 12
  • I'm having the same issue at home and work. I've deleted every instance of chromedriver off the computer and it keeps downloading 114 instead of 116. Also, I'm using C# bindings and [Selenium Manager](https://www.selenium.dev/blog/2022/introducing-selenium-manager/) (instead of WebDriverManager). – JeffC Aug 19 '23 at 03:31
  • Well... as soon as I state the above and then start trying to fix it... it starts working. It finally downloaded 116. I would suggest you try it a few more times. Run `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. – JeffC Aug 19 '23 at 03:52
  • Update Selenium to the current version and you no longer need WebDriverManager and it should download 116 correctly. Apparently ChromeDriver's download location changed recently and needed a code update. – JeffC Aug 19 '23 at 19:44

6 Answers6

7

Please use Latest version of WebDriverManager. WDM version 5.4.1 has resolved this issue for me. Google has release new Chrome flavor that specifically targets web app testing and automation use cases which means Chrome Driver download URL has changed from chrome version 115

Reference: https://developer.chrome.com/blog/chrome-for-testing/

WebDriver download URL : https://googlechromelabs.github.io/chrome-for-testing/

4

I created a new subsection in the know issues section of the WebDriverManager doc (see Support for chromedriver 115+).

In summary, the solution to this problem is to bump WebDriverManager to the latest version (5.5.3 currently). Also, to ensure that the wrong version has not been cached in the resolution cache (more info on doc), you can refresh completely the cache folder (at least once) as follows:

WebDriverManager.chromedriver().clearDriverCache().setup();
Boni García
  • 4,618
  • 5
  • 28
  • 44
1

No need to use WebDriverManager from 4.6.0 version Selenium Manager will help you directly download and match the browser driver version, upgrade your selenium to 4.11.0

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 28 '23 at 12:01
0

For Mac and using NPM webdriver-manager package,

  1. Download same version of chrome-driver as per your browser version. https://googlechromelabs.github.io/chrome-for-testing/
  2. Go to cd /usr/local/lib/node_modules/protractor/node_modules/webdriver-manager/selenium.
  3. Copy downloaded chrome-driver to this folder.
  4. Rename downloaded chrome-driver version with your latest selenium chrome driver version. Ex -> downloaded chrome-driver to chromedriver_114.0.5735.90.
  5. After renaming, convert it to zip folder as well.
  6. Allow Anyway it from Security & Privacy.

Now, you would be using latest chrome driver for selenium with your latest browser. You would not see following error "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".

Don't run webdriver-manager update cmd after renaming otherwise it will overwrite older version of chrome-driver

0

This issue can be mitigated by using Selenium Webdriver version 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/");
-1
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();
    }

}
  • 1
    What in the world is all this code supposed to do? Selenium has a [Selenium Manager](https://www.selenium.dev/blog/2022/introducing-selenium-manager/) that is supposed to automatically download and use the matching browser driver for you. – JeffC Aug 19 '23 at 03:54
  • you need to figure it out first and then click that it is unusable, the manager downloads the drivers from the standard site, and starting from version 115 and higher, the site where the drivers are stored has changed and this code determines the version of chrome and downloads from the new site (https://googlechromelabs.github.io /chrome-for-testing/) of the driver and installs them in the same directory as the manager if the manager could not find suitable drivers saves the new version value to a file and the next time it starts the algorithm only if the driver version is outdated – Артем Евграфов Aug 19 '23 at 09:52