一、工具准备
- Firefox浏览器(本教程版本为45.5,记得关掉它的自动更新。)
- JDK-1.8
- Eclipse
二、环境搭建
·配置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">启动selenium服务:
将下载的zip包解压,然后在命令行进入解压文件的目录,输入
java -jar seleniun-server-standalone-3.0.1.jar
如图所示表示启动服务成功:
<img src="http://upload-images.jianshu.io/upload_images/2529410-0b98249199570819.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="启动selenium服务">
·配置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
如图操作,导入所需jar包
<img src="http://upload-images.jianshu.io/upload_images/2529410-dfab0ff1674e3ba3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="导入jar包">
<img src="http://upload-images.jianshu.io/upload_images/2529410-4e98af5d849c610d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="导入jar包">
·下载selenium3使用firefox时所需的驱动
下载地址 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驱动">
至此,项目环境搭建完成。
三、测试示例
新建一个名为test.java 的文件。
实现效果:打开百度首页,输入“Selenium”,点击搜索。
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驱动
System.setProperty("webdriver.firefox.marionette","C:\\Users\\Jaden\\Desktop\\Test\\jar\\geckodriver.exe");
//新建一个firefox浏览器实例
WebDriver driver = new FirefoxDriver();
//打开百度首页
driver.get("http://www.baidu.com");
//根据id获取输入框
WebElement textInput = driver.findElement(By.id("kw"));
//在输入框输入“Selenium”
textInput.sendKeys("Selenium");
//根据id获取“百度一下”按钮
WebElement submit = driver.findElement(By.id("su"));
//点击按钮
submit.click();
}
}