How to load ChromeDriver binary from class?

Several sources refer to downloading ChromeDriver binary from the class path, but I have not developed how to do this if the binary is not in the root directory of the path.

To specify the path to the binary, you need to set the system property "webdriver.chrome.driver". First I tried:

System.setProperty("webdriver.chrome.driver", "drivers/Chrome/chromedriver.exe");

But I have an error, and it looks like he was looking for a driver in a location "C:\<working directory of my application process>\drivers\Chrome\chromedriver.exe". Here, the working directory was actually the directory in which my source code is stored.

Then I tried:

System.setProperty("webdriver.chrome.driver", "/drivers/Chrome/chromedriver.exe");

However, the same thing happened - this time he looked in "C:\drivers\Chrome\chromedriver.exe".

How do I get ChromeDriver to look for the ChromeDriver binary in the classpath when using the "webdriver.chrome.driver" property or any other way to configure it?

+4
source share
3 answers

In the end, I found that it ChromeDriverdoes not support relative access of the class to its binary. However, you can convert the relative classpath string to the system path, and then directly load it, bypassing the system property.

URL url = this.getClass().getClassLoader().getResource(classpathRelativeLocation);
File file = new File(url.getFile()); // Strangely, URL.getFile does not return a File
ChromeDriverService.Builder bldr = (new ChromeDriverService.Builder())
                                   .usingDriverExecutable(file)
                                   .usingAnyFreePort();
ChromeDriver driver = new ChromeDriver(bldr.build());
+4
source

, . chromedriver.exe classpath, , . setProperty. , chromedriver.exe Java Build Path /src/main/resources

, classpath

public class App 
{
private static final String CHROME_DRIVER_PATH=App.class.getClassLoader().getResource("chromedriver.exe").getPath(); 
    public static void main( String[] args ) throws InterruptedException
    {
        System.setProperty("webdriver.chrome.driver", CHROME_DRIVER_PATH);
        WebDriver driver=new ChromeDriver();
        Thread.sleep(2000);
        driver.close();        
    }
}
0

In my opinion, it should work with the following full path:

 System.SetProperty("webdriver.chrome.driver", @"D:/drivers/Chrome/chromedriver.exe");
 WebDriver driver = new ChromeDriver();              
 driver.get("http://www.google.com");

I hope this helps you!

-2
source

All Articles