为什么我无法为我的Selenium网络驱动程序 (java) 设置系统属性?


public class Main {
static Locators Locators = new Locators();
static WebDriver driver = new ChromeDriver();
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\currentuser\chromedriver.exe");
...
}

我得到以下异常:

Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html
at com.google.common.base.Preconditions.checkState(Preconditions.java:847)
at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:134)
at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:35)
at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:159)
at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:355)
at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:94)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
at Main.<clinit>(Main.java:11)

在这条线上:

static WebDriver driver = new ChromeDriver();

为什么我会想到我已经定义了sys.setproperty,以及如何在代码中修复它?

正如@XiaoYu所提到的,您正在尝试在系统属性中设置路径之前创建chrome驱动程序实例。您可以更新如下所示的代码

public class Main {
static Locators Locators = new Locators();
static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\currentuser\chromedriver.exe");
driver =  new ChromeDriver();
}

尝试跟踪代码

public class Main {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\currentuser\chromedriver.exe");
...
// init here
Locators Locators = new Locators();
WebDriver driver = new ChromeDriver();
}
}

在您的代码中,"WebDriver driver=new ChromeDriver((;"是在"System.setProperty…."之前执行的,这就是您出现此错误的原因。

最新更新