轉自http://blog.sina.com.cn/s/blog_6966650401012a5f.html
1.啓動瀏覽器
A.firefox
//打開默認路徑的firefox(路徑指的是 firefox
//打開指定路徑的firefox,方法1
//打開指定路徑的firefox,方法2
B.ie
//打開ie
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.關閉瀏覽器
下載地址: http://code.google.com/p/chromedriver/downloads/list
//打開chrome
另一種啓動chrome 的方法
wiki介紹:http://code.google.com/p/selenium/wiki/ChromeDriver
//打開chrome
Chromium介紹:http://code.google.com/p/chromium/
2.頁面跳轉url
String url = "http://www.baidu.com";
WebDriver driver = new FirefoxDriver();
A//用get方法
B//用navigate方法,然後再調用to方法,chrome不支持這種方法
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() 返回當前頁面的源碼
5.總結
操作瀏覽器的主要方法都來自org.openqa.selenium.WebDriver這個接口中。
源代碼這些方法都是在org.openqa.selenium.remote.RemoteWebDriver這個類中實現的,然後不同瀏覽的driver類繼承RemoteWebDriver。
A.//用quit方法
B.//用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。