Selenium webdriver 之浏览器操作

上一篇 / 下一篇  2014-05-21 10:44:46 / 个人分类:Selenium2

转自http://blog.sina.com.cn/s/blog_6966650401012a5f.html

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。

TAG:

 

评分:0

我来说两句

Open Toolbar