前面的答案都是正确的。以下是对问题和解决方案的深入探讨。
以 Selenium 中的驱动构造函数为例
WebDriver driver = new ChromeDriver();
搜索驱动程序可执行文件,在这种情况下,Google Chrome 驱动程序搜索 Chrome 驱动程序可执行文件。如果服务找不到可执行文件,则抛出异常。
这就是异常的来源(注意检查状态方法)
/**
*
* @param exeName Name of the executable file to look for in PATH
* @param exeProperty Name of a system property that specifies the path to the executable file
* @param exeDocs The link to the driver documentation page
* @param exeDownload The link to the driver download page
*
* @return The driver executable as a {@link File} object
* @throws IllegalStateException If the executable not found or cannot be executed
*/
protected static File findExecutable(
String exeName,
String exeProperty,
String exeDocs,
String exeDownload) {
String defaultPath = new ExecutableFinder().find(exeName);
String exePath = System.getProperty(exeProperty, defaultPath);
checkState(exePath != null,
"The path to the driver executable must be set by the %s system property;"
+ " for more information, see %s. "
+ "The latest version can be downloaded from %s",
exeProperty, exeDocs, exeDownload);
File exe = new File(exePath);
checkExecutable(exe);
return exe;
}
以下是引发异常的检查状态方法:
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*/
public static void checkState(
boolean b,
@Nullable String errorMessageTemplate,
@Nullable Object p1,
@Nullable Object p2,
@Nullable Object p3) {
if (!b) {
throw new IllegalStateException(format(errorMessageTemplate, p1, p2, p3));
}
}
解决方案:在创建驱动对象之前设置系统属性,如下所示。
System.setProperty("webdriver.gecko.driver", "path/to/chromedriver.exe");
WebDriver driver = new ChromeDriver();
以下是驱动服务搜索驱动程序可执行文件的代码 sn-p(适用于 Chrome 和 Firefox):
铬:
@Override
protected File findDefaultExecutable() {
return findExecutable("chromedriver", CHROME_DRIVER_EXE_PROPERTY,
"https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver",
"http://chromedriver.storage.googleapis.com/index.html");
}
火狐:
@Override
protected File findDefaultExecutable() {
return findExecutable(
"geckodriver", GECKO_DRIVER_EXE_PROPERTY,
"https://github.com/mozilla/geckodriver",
"https://github.com/mozilla/geckodriver/releases");
}
其中 CHROME_DRIVER_EXE_PROPERTY = "webdriver.chrome.driver"
和 GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver"
其他浏览器的情况类似,以下是可用浏览器实现列表的快照: