Selenium WebDriver廣泛用於web自動化,這篇文章主要是介紹瀏覽器的一些操作。主要以Firefox為例, 因Chrome Driver是Chromium 項目自己支持和維護的,所以需另外下載安裝Chrome Driver,詳細介紹查閱wiki 。注:但它的操作方式與firefox是類似。
打開瀏覽器
兩種方式打開firefox。
1 package com.annieyu.test;
3 import org.openqa.selenium.firefox.FirefoxBinary; 4 import org.openqa.selenium.firefox.FirefoxDriver; 5 import org.openqa.selenium.ie.InternetExplorerDriver; 6 import org.openqa.selenium.WebDriver; 7 8 9 public class OpenBrowsers { 10 public static void main(String[] args){ 11 12 // 打開默認路徑的firefox 13 WebDriver driver = new FirefoxDriver(); 14 15 // 方法1:打開指定路徑下的firefox 16 System.setProperty("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"); 17 WebDriver driver1 = new FirefoxDriver(); 18 19 // 方法2:打開指定路徑下的firefox 20 File firefoxBinaryPath = new File("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"); 21 FirefoxBinary firefoxBinary = new FirefoxBinary(firefoxBinaryPath); 22 WebDriver driver2 = new FirefoxDriver(firefoxBinary, null); 23 24 // 打開ie瀏覽器 25 WebDriver ieDriver = new InternetExplorerDriver(); 26 } 27 }
從瀏覽器打開URL
有兩種方式,打開URL。
1 package com.annieyu.test; 2 import org.openqa.selenium.firefox.FirefoxDriver; 3 import org.openqa.selenium.WebDriver; 4 5 public class OpenURL { 6 public static void main(String[] args) { 7 // 打開默認路徑的firefox 8 WebDriver driver = new FirefoxDriver(); 9 10 // 定義要打開的URL路徑 11 String url = "http://www.taobao.com"; 12 13 // 方法1:get方法,打開URL 14 driver.get(url); 15 16 // 方法2:用navigate方法,然后調用to方法打開URL 17 driver.navigate().to(url); 18 19 } 20 }
關閉瀏覽器
兩種方式,關閉瀏覽器,詳細見下:
1 package com.annieyu.test; 2 3 import org.openqa.selenium.WebDriver; 4 import org.openqa.selenium.firefox.FirefoxDriver; 5 6 public class CloseBrowsers { 7 public static void main(String[] args) { 8 WebDriver driver = new FirefoxDriver(); 9 10 // 方法1:關閉瀏覽器 11 driver.close(); 12 13 // 方法2:關閉瀏覽器 14 driver.quit(); 15 16 } 17 18 }
獲取頁面的Title、URL、SOURCE
1 package com.annieyu.test; 2 3 import org.openqa.selenium.WebDriver; 4 import org.openqa.selenium.firefox.FirefoxDriver; 5 6 public class GetPageResource { 7 public static void main(String[] args) { 8 WebDriver driver = new FirefoxDriver(); 9 10 String url = "http://www.taobao.com"; 11 12 // 打開URL 13 driver.get(url); 14 15 // 獲取頁面的title 16 String title = driver.getTitle(); 17 18 // 獲取當前頁面的url 19 String currentURL = driver.getCurrentUrl(); 20 21 // 獲取頁面的源碼 22 String sourceCode = driver.getPageSource(); 23 24 System.out.println(title + url); 25 } 26 }