环境准备

1、下载火狐驱动 位置:https://cdn.npm.taobao.org/dist/geckodriver/ (我这里选择 v0.21.0 版本,如果版本太旧程序执行可能会报错)

2、将驱动复制到 火狐浏览器的安装目录

selenium自动化测试详细教程_示例

代码编写
创建maven工程引入selenium依赖如下:

<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.14.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.14.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>

编写代码并执行

@Test
public void test() throws Exception {

System.setProperty("webdriver.gecko.driver","C:/Program Files (x86)/Mozilla Firefox/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);
driver.get("http://www.baidu.com");
driver.manage().window().maximize();
driver.findElement(By.id("kw")).sendKeys("Selenium");
driver.findElement(By.id("su")).click();
Thread.sleep(1000);
System.out.println(driver.getTitle().contains("Selenium"));
driver.quit();
}

执行过程中,火狐浏览器自动打开并完成了搜索操作

selenium自动化测试详细教程_java_02

其他更详细内容见下文
​​​ https://wizardforcel.gitbooks.io/selenium-doc/content/wiki/advanced-user-interactions.html​