官方文档中说为了避免在每次实例化时都启动ChromeDriver,可以使用RemoteWebDriver,通过ChromeDriverService去控制,同时给出了例子,这样可以减少启动server,减少内存的开销
public class StartUpDemo {
@Test
public void startServer(){
// 声明一个DriverServer,只启动一次server,避免多次启动server,节省内存
ChromeDriverService service=new ChromeDriverService.Builder()
.usingDriverExecutable(new File("./driver/chromedriver"))
.usingAnyFreePort().build();
try {
service.start();
} catch (IOException e) {
e.printStackTrace();
}
URL url = service.getUrl();
openUrl(url,"http://www.baidu.com");
openUrl(url,"http://www.qq.com");
service.stop();
}
public void openUrl(URL url,String urlPath){
WebDriver driver=new RemoteWebDriver(url,DesiredCapabilities.chrome());
driver.get(urlPath);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.close();
}
}
只启动了一次server
普通的做法会多次启动server
@Test
public void normal(){
openUrlNormal("http://www.baidu.com");
openUrlNormal("http://www.qq.com");
}
public void openUrlNormal(String urlPath){
System.setProperty("webdriver.chrome.driver","./driver/chromedriver");
WebDriver driver=new ChromeDriver();
driver.get(urlPath);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.close();
}