当我运行以下代码时,显示以下错误:org.openqa.selenium.remote.UnreachableBrowserException:无法启动新会话。可能的原因是远程服务器的无效地址或浏览器启动失败。
Chrome浏览器尚未启动。
// baseClass.java:
public class BaseClass {
//ThreadLocal will keep local copy of driver
public static ThreadLocal<RemoteWebDriver> dr = new ThreadLocal<RemoteWebDriver>();
@BeforeTest
//Parameter will get browser from testng.xml on which browser test to run
@Parameters("myBrowser")
public void beforeClass(String myBrowser) throws MalformedURLException{
try {
RemoteWebDriver driver = null;
if(myBrowser.equals("chrome")){
DesiredCapabilities capability = new DesiredCapabilities().chrome();
capability.setBrowserName("chrome");
capability.setPlatform(Platform.WINDOWS);
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
}
else if(myBrowser.equals("firefox")){
DesiredCapabilities capability = new DesiredCapabilities().firefox();
capability.setBrowserName("firefox");
capability.setPlatform(Platform.WINDOWS);
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
}
//setting webdriver
setWebDriver(driver);
getDriver().manage().window().maximize();
getDriver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}catch (Exception ex){
System.out.println(ex.toString());
}
}
public WebDriver getDriver() {
return dr.get();
}
public void setWebDriver(RemoteWebDriver driver) {
dr.set(driver);
}
@AfterClass
public void afterClass(){
getDriver().quit();
dr.set(null);
}
}
答案 0 :(得分:1)
在初始化RemoteWebDriver之前,您必须为chrome / gecko驱动程序设置系统属性。像,
if(myBrowser.equals("chrome")){
DesiredCapabilities capability = new DesiredCapabilities().chrome();
capability.setBrowserName("chrome");
capability.setPlatform(Platform.WINDOWS);
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver\\chromedriver.exe");
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
}
else if(myBrowser.equals("firefox")){
DesiredCapabilities capability = new DesiredCapabilities().firefox();
capability.setBrowserName("firefox");
capability.setPlatform(Platform.WINDOWS);
System.setProperty("webdriver.gecko.driver", "C:\\geckodriver\\geckodriver.exe");
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
}