Selenium(三)——webdriver 之瀏覽器操作

轉自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。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章