WebDriverManager setup failing to download chromedriver 116
Asked Answered
L

7

11

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

Lucrative answered 18/8, 2023 at 20:49 Comment(3)
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 (instead of WebDriverManager).Bondswoman
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.Bondswoman
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.Bondswoman
G
11

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/

Georgiageorgian answered 20/8, 2023 at 13:46 Comment(3)
is the latest webdriver manager is version 12.1.9?Isaac
I have issue trying to update latest chrome driver 116 with webdriver manager. it is only update 114Isaac
hey... i'm having a similar issue. how do i check what webDriverManager version do i have? i just wanna make sure before upgrading... thanks!Racemic
P
9

I created a new subsection in the know issues section of the WebDriverManager doc.

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();
Prank answered 22/8, 2023 at 12:46 Comment(2)
You're the man. This fixed it for me. Had a lot of trouble with webdriver manager. Thank you.Geriatric
@Boni Garcia, I have the same issue for python, any workaround?Henshaw
C
3

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

Costanza answered 20/8, 2023 at 9:41 Comment(1)
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.Disgrace
C
2

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/");
Conchiolin answered 25/8, 2023 at 12:11 Comment(0)
C
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

Crossness answered 24/8, 2023 at 1:22 Comment(0)
T
0

The included selenium manager automatically handles driver management now. Here's how you can set things up if you need to customize your driver with additional options:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

service = Service()
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# ... Automate something here
driver.quit()

You can also use the SeleniumBase driver manager, which automatically downloads a driver to match your browser if it's not present:

from seleniumbase import Driver

driver = Driver(browser="chrome")
driver.get("https://www.google.com")
driver.quit()
Typesetter answered 19/9, 2023 at 14:30 Comment(0)
N
-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();
    }

}
Nodical answered 19/8, 2023 at 3:47 Comment(2)
What in the world is all this code supposed to do? Selenium has a Selenium Manager that is supposed to automatically download and use the matching browser driver for you.Bondswoman
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 (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 outdatedHm

© 2022 - 2024 — McMap. All rights reserved.