一击蹲、工具準(zhǔn)備
- Firefox瀏覽器(本教程版本為45.5署拟,記得關(guān)掉它的自動(dòng)更新。)
- JDK-1.8
- Eclipse
二歌豺、環(huán)境搭建
·配置Selenium RC
下載 selenium-server-standalone-3.0.1
下載地址 http://www.seleniumhq.org/download/
<img src="http://upload-images.jianshu.io/upload_images/2529410-022b5f8db9a36c28.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="下載selenium-server-standalone-3.0.1">啟動(dòng)selenium服務(wù):
將下載的zip包解壓推穷,然后在命令行進(jìn)入解壓文件的目錄,輸入
java -jar seleniun-server-standalone-3.0.1.jar
如圖所示表示啟動(dòng)服務(wù)成功:
<img src="http://upload-images.jianshu.io/upload_images/2529410-0b98249199570819.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="啟動(dòng)selenium服務(wù)">
·配置Selenium Webdriver
下載 selenium-java-3.0.1
下載地址 http://www.seleniumhq.org/download/
<img src="http://upload-images.jianshu.io/upload_images/2529410-c1388f3be2a10c2f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="下載selenium-java-3.0.1">在Eclipse中新建Java Project
如圖操作类咧,導(dǎo)入所需jar包
<img src="http://upload-images.jianshu.io/upload_images/2529410-dfab0ff1674e3ba3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="導(dǎo)入jar包">
<img src="http://upload-images.jianshu.io/upload_images/2529410-4e98af5d849c610d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="導(dǎo)入jar包">
·下載selenium3使用firefox時(shí)所需的驅(qū)動(dòng)
下載地址 https://github.com/mozilla/geckodriver/releases/tag/v0.9.0
<img src="http://upload-images.jianshu.io/upload_images/2529410-122f93872345110c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="下載geckodriver驅(qū)動(dòng)">
至此馒铃,項(xiàng)目環(huán)境搭建完成。
三痕惋、測(cè)試示例
新建一個(gè)名為test.java 的文件区宇。
實(shí)現(xiàn)效果:打開(kāi)百度首頁(yè),輸入“Selenium”值戳,點(diǎn)擊搜索议谷。
package test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class baidu {
public static void main(String[] args){
//引入geckodriver驅(qū)動(dòng)
System.setProperty("webdriver.firefox.marionette","C:\\Users\\Jaden\\Desktop\\Test\\jar\\geckodriver.exe");
//新建一個(gè)firefox瀏覽器實(shí)例
WebDriver driver = new FirefoxDriver();
//打開(kāi)百度首頁(yè)
driver.get("http://www.baidu.com");
//根據(jù)id獲取輸入框
WebElement textInput = driver.findElement(By.id("kw"));
//在輸入框輸入“Selenium”
textInput.sendKeys("Selenium");
//根據(jù)id獲取“百度一下”按鈕
WebElement submit = driver.findElement(By.id("su"));
//點(diǎn)擊按鈕
submit.click();
}
}