selenium之操做ChromeDriver

selenium操做chrome浏览器须要有ChromeDriver驱动来协助。html

什么是ChromeDriver?web

ChromeDriver是Chromium team开发维护的,它是实现WebDriver有线协议的一个单独的服务。ChromeDriver经过chrome的自动代理框架控制浏览器,ChromeDriver只与12.0.712.0以上版本的chrome浏览器兼容。chrome

那么要想selenium成功的操做chrome浏览器须要经历以下步骤:api

一、下载ChromeDriver驱动包(下载地址:http://chromedriver.storage.googleapis.com/index.html?path=2.7/浏览器

 

注意阅读note.txt下载与本身所使用浏览器一致版本的驱动包。app

二、指定ChromeDriver所在位置,能够经过两种方法指定:框架

1)经过配置ChromeDriver.exe位置到path环境变量实现。测试

2)经过webdriver.chrome.driver.系统属性实现。实现代码以下:ui

System.setProperty("webdriver.chrome.driver", "C:\\Documents and Settings\\Administrator\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chromedriver.exe");

三、最后须要作的就是建立一个新的ChromeDriver的实例。google

WebDriver driver = new ChromeDriver();
driver.get("http://www.baidu.com/"); 

至此咱们就能够经过chrome浏览器来执行咱们的自动化代码了。

完整实例代码以下:

public static void main(String[] args) {

           // TODO Auto-generated method stub

//设置访问ChromeDriver的路径

System.setProperty("webdriver.chrome.driver", "C:\\Documents and Settings\\Administrator\\LocalSettings\\Application Data\\Google\\Chrome\\Application\\chromedriver.exe");

           WebDriver driver = new ChromeDriver();

           driver.get("http://www.baidu.com/");

 

}

btw:

chrome浏览器在各个系统默认位置:

OS Expected Location of Chrome
Linux /usr/bin/google-chrome1
Mac /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome
Windows XP %HOMEPATH%\Local Settings\Application Data\Google\Chrome\Application\chrome.exe
Windows Vista C:\Users\%USERNAME%\AppData\Local\Google\Chrome\Application\chrome.exe

 

 

执行以上代码你会发现ChromeDriver仅是在建立是启动,调用quit时关闭浏览器,ChromeDriver是轻量级的服务若在一个比较大的测试套件中频繁的启动关闭,会增长一个比较明显的延时致使浏览器进程不被关闭的状况发生,为了不这一情况咱们能够经过ChromeDriverService来控制ChromeDriver进程的生死,达到用完就关闭的效果避免进程占用状况出现(Running the server in a child process)。

具体实现以下:

ChromeDriverService service = new ChromeDriverService.Builder() .usingChromeDriverExecutable(new File("E:\\Selenium WebDriver\\chromedriver_win_23.0.1240.0\\chromedriver.exe")).usingAnyFreePort().build(); service.start(); driver = new ChromeDriver(); driver.get("http://www.baidu.com"); driver.quit(); // 关闭 ChromeDriver 接口 service.stop();
相关文章
相关标签/搜索