selenium webdriver對瀏覽器的簡單操做java
打開一個測試瀏覽器
對瀏覽器進行操做首先須要打開一個瀏覽器,接下來才能對瀏覽器進行操做。但要注意的是,由於Chrome Driver是Chromium 項目本身支持和維護的,因此你必需另外下載安裝Chrome Driver,詳細介紹查下他們的wiki 。web
- import java.io.File;
-
- import org.openqa.selenium.WebDriver;
- import org.openqa.selenium.firefox.FirefoxBinary;
- import org.openqa.selenium.firefox.FirefoxDriver;
- import org.openqa.selenium.ie.InternetExplorerDriver;
-
- public class OpenBrowsers {
-
-
- public static void main(String[] args) {
-
- WebDriver diver = new FirefoxDriver();
-
-
- System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");
- WebDriver dr = new FirefoxDriver();
-
-
- File pathToFirefoxBinary = new File("D:\\Program Files\\Mozilla Firefox\\firefox.exe");
- FirefoxBinary firefoxbin = new FirefoxBinary(pathToFirefoxBinary);
- WebDriver driver1 = new FirefoxDriver(firefoxbin,null);
-
-
- WebDriver ie_driver = new InternetExplorerDriver();
-
-
- System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
- System.setProperty("webdriver.chrome.bin",
- "C:\\Documents and Settings\\gongjf\\Local Settings"
- +"\\Application Data\\Google\\Chrome\\Application\\chrome.exe");
-
- }
-
- }
打開指定路經ie和chrome方法和ff同樣。chrome
打開1個具體的url
打開一個瀏覽器後,咱們須要跳轉到特定的url下,看下面代碼:瀏覽器
- import org.openqa.selenium.WebDriver;
- import org.openqa.selenium.firefox.FirefoxDriver;
-
- public class OpenUrl {
- public static void main(String []args){
- String url = "http://www.51.com";
- WebDriver driver = new FirefoxDriver();
-
-
- driver.get(url);
-
-
- driver.navigate().to(url);
- }
- }
如何關閉瀏覽器
測試完成後,須要關閉瀏覽器學習
- import org.openqa.selenium.WebDriver;
- import org.openqa.selenium.firefox.FirefoxDriver;
-
- public class CloseBrowser {
- public static void main(String []args){
- String url = "http://www.51.com";
- WebDriver driver = new FirefoxDriver();
-
- driver.get(url);
-
-
- driver.quit();
-
-
- driver.close();
- }
- }
如何返回當前頁面的url和title
有時候咱們須要返回當前頁面的url或者title作一些驗證性的操做等。代碼以下:測試
- import org.openqa.selenium.WebDriver;
- import org.openqa.selenium.firefox.FirefoxDriver;
-
- public class GetUrlAndTitle {
- public static void main(String []args){
- String url = "http://www.51.com";
- WebDriver driver = new FirefoxDriver();
-
- driver.get(url);
-
-
- String title = driver.getTitle();
-
-
- String currentUrl = driver.getCurrentUrl();
-
-
- System.out.println(title+"\n"+currentUrl);
-
- }
- }
其餘方法
- getWindowHandle() 返回當前的瀏覽器的窗口句柄
- getWindowHandles() 返回當前的瀏覽器的全部窗口句柄
- getPageSource() 返回當前頁面的源碼
小結
從上面代碼能夠看出操做瀏覽器的主要方法都來自org.openqa.selenium.WebDriver這個接口中。看了一下源代碼這些方法都是在org.openqa.selenium.remote.RemoteWebDriver這個類中實現的,而後不一樣瀏覽的driver類繼承RemoteWebDriver。ui