selenium之操作ChromeDriver

2014-04-15  文晶 

selenium操作chrome浏览器需要有ChromeDriver驱动来协助。
什么是ChromeDriver?
ChromeDriver是Chromium team开发维护的,它是实现WebDriver有线协议的一个单独的服务。ChromeDriver通过chrome的自动代理框架控制浏览器,ChromeDriver只与12.0.712.0以上版本的chrome浏览器兼容。
那么要想selenium成功的操作chrome浏览器需要经历如下步骤:
1、下载ChromeDriver驱动包(下载地址: http://chromedriver.storage.googleapis.com/index.html?path=2.7/

注意阅读note.txt下载与自己所使用浏览器一致版本的驱动包。
2、指定ChromeDriver所在位置,可以通过两种方法指定:
1)通过配置ChromeDriver.exe位置到path环境变量实现。
2)通过webdriver.chrome.driver.系统属性实现。实现代码如下:
System.setProperty("webdriver.chrome.driver", "C:\\Documents and Settings\\Administrator\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chromedriver.exe");
3、最后需要做的就是创建一个新的ChromeDriver的实例。
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();


14952°/149529 人阅读/0 条评论 发表评论

登录 后发表评论