假設 Chrome/Firefox/IE 瀏覽器安裝的是 32 位版本,對應的瀏覽器驅(qū)動放在 D:\WebDrivers 目錄。
Chrome 瀏覽器
import org.openqa.selenium.WebDriver; // 瀏覽器驅(qū)動操作接口
import org.openqa.selenium.By; // 頁面元素定位類
import org.openqa.selenium.chrome.ChromeDriver; // Chrome 瀏覽器驅(qū)動類
public class SeleniumChrome {
public static void main(String[] args) throws InterruptedException {
// 設置 Chrome 瀏覽器可執(zhí)行文件的位置,一般可以不用設置
String browserPath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
System.setProperty("webdriver.chrome.bin", browserPath);
// 設置 Chrome 瀏覽器驅(qū)動的位置
String driverPath = "D:\\WebDrivers\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", driverPath);
// 關閉 Chrome 瀏覽器驅(qū)動的日志輸出
System.setProperty("webdriver.chrome.silentOutput", "true");
// 創(chuàng)建 Chrome 瀏覽器驅(qū)動對象
WebDriver driver = new ChromeDriver();
// 打開百度首頁
driver.get("https://www.baidu.com");
// 定位搜索輸入框輸入查找的內(nèi)容
driver.findElement(By.id("kw")).sendKeys("Chrome");
// 等待 3 秒
Thread.sleep(3000);
// 關閉瀏覽器窗口
driver.close();
}
}
Firefox 瀏覽器
import org.openqa.selenium.WebDriver; // 瀏覽器驅(qū)動操作接口
import org.openqa.selenium.By; // 頁面元素定位類
import org.openqa.selenium.firefox.FirefoxDriver; // Firefox 瀏覽器驅(qū)動類
public class SeleniumFirefox {
public static void main(String[] args) throws InterruptedException {
// 設置 Firefox 瀏覽器可執(zhí)行文件的位置,一般可以不用設置
String browserPath = "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe";
System.setProperty("webdriver.firefox.bin", browserPath);
// 設置 Firefox 瀏覽器驅(qū)動的位置
String driverPath = "D:\\WebDrivers\\geckodriver.exe";
System.setProperty("webdriver.gecko.driver", driverPath);
// 默認日志信息輸出很多,可以關閉日志
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,"/dev/null");
// 創(chuàng)建 Firefox 瀏覽器驅(qū)動對象
WebDriver driver = new FirefoxDriver();
// 打開百度首頁
driver.get("https://www.baidu.com");
// 定位搜索輸入框輸入查找的內(nèi)容
driver.findElement(By.id("kw")).sendKeys("Firefox");
// 等待 3 秒
Thread.sleep(3000);
// 關閉瀏覽器窗口
driver.close();
}
}
IE 瀏覽器
import org.openqa.selenium.WebDriver; // 瀏覽器驅(qū)動操作接口
import org.openqa.selenium.By; // 頁面元素定位類
import org.openqa.selenium.ie.InternetExplorerDriver; // IE 瀏覽器驅(qū)動類
public class SeleniumIE {
public static void main(String[] args) throws InterruptedException {
// 設置 IE 瀏覽器可執(zhí)行文件的位置,一般可以不用設置
String browserPath = "C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe";
System.setProperty("webdriver.ie.bin", browserPath);
// 設置 IE 瀏覽器驅(qū)動的位置
String driverPath = "D:\\WebDrivers\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver", driverPath);
// 創(chuàng)建 IE 瀏覽器驅(qū)動對象
WebDriver driver = new InternetExplorerDriver();
// 打開百度首頁
driver.get("https://www.baidu.com");
// 定位搜索輸入框輸入查找的內(nèi)容
driver.findElement(By.id("kw")).sendKeys("IE");
// 等待 3 秒
Thread.sleep(3000);
// 關閉瀏覽器窗口
driver.close();
}
}