selenium WebDriver 浏览器操作
1.启动浏览器 A.firefox //打开默认路径的firefox(路径指的是 firefox 的安装路径) WebDriver diver = new FirefoxDriver(); //打开指定路径的firefox,方法1 System.setProperty("webdriver.firefox.bin","D:\ProgramFiles\Mozilla Firefox\firefox.exe"); WebDriver dr = new FirefoxDriver(); //打开指定路径的firefox,方法2 File pathToFirefoxBinary = new File("D:\Program Files\Mozilla Firefox\firefox.exe"); FirefoxBinary firefoxbin = new FirefoxBinary(pathToFirefoxBinary); WebDriver driver1 = new FirefoxDriver(firefoxbin,null);
B.ie //打开ie WebDriver ie_driver = new InternetExplorerDriver(); C.chrome 因为Chrome Driver是Chromium 项目自己支持和维护的,所以你必需另外下载chromedriver.exe,放在目录下C:\WINDOWS\system32 下载地址: http://code.google.com/p/chromedriver/downloads/list //打开chrome WebDriver driver = new ChromeDriver(); 另一种启动chrome 的方法 wiki介绍:http://code.google.com/p/selenium/wiki/ChromeDriver //打开chrome System.setProperty("webdriver.chrome.driver", "D:\chromedriver.exe"); System.setProperty("webdriver.chrome.bin", C:\Documents and Settings\fy\Local Settings" +"\Application Data\Google\Chrome\Application\chrome.exe"); Chromium介绍:http://code.google.com/p/chromium/
2.页面跳转url String url = "http://www.baidu.com"; WebDriver driver = new FirefoxDriver(); A//用get方法 driver.get(url); B//用navigate方法,然后再调用to方法,chrome不支持这种方法 driver.navigate().to(url);
3.关闭浏览器 //quit 关闭所有页面 close 关闭本次执行打开的页面 A.//用quit方法 driver.quit(); B.//用close方法 driver.close();
4.获取页面信息 //得到title String title = driver.getTitle(); //得到当前页面url String currentUrl = driver.getCurrentUrl(); getWindowHandle() 返回当前的浏览器的窗口句柄 getWindowHandles() 返回当前的浏览器的所有窗口句柄 getPageSource() 返回当前页面的源码 //String s=driver.getPageSource();s=s.substring(s.indexOf("{"), s.indexOf("}")); //System.out.println("当前页面的源码:"+s);
5.总结 操作浏览器的主要方法都来自org.openqa.selenium.WebDriver这个接口中。 源代码这些方法都是在 org.openqa.selenium.remote.RemoteWebDriver这个类中实现的,然后不同浏览的driver类继承 RemoteWebDriver。