java调用selenium_Java调用Selenium WebDriver在Firefox下测试示例
本文使用Java的Selenium WebDriver来做一个简单的测试示例,主要介绍如何调用Firefox浏览器测试。
步骤
Step 1:下载Selenium WebDriver
去 Selenium官网 下载最新版本的Java client,我这里下载的最新版本是3.1.0,下载的是一个压缩包,解压缩以后里面包括一个lib目录以及一个client-combined-3.1.0-nodeps.jar,后面都需要引入。
也可以通过maven在项目中直接引入,而不用下载:
org.seleniumhq.selenium
selenium-java
3.1.0
Step 2 :下载geckodriver
去 mozilla/geckodriver 中下载最新的release版本的geckodriver,我这里下载的是v0.14.0,我暂时将其放到跟selenium-java-3.1.0的相同目录,如下图:
Step 3:编写java代码测试
新建Java工程,引入client-combined-3.1.0-nodeps.jar及其lib文件夹下的所有依赖jar,编写相应的java代码,目录结构及代码如下:
FirefoxUtils.java源码如下:
package utils;
import java.io.File;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
/**
* Firefox工具类
*
* @author dehua.ye
*
*/
public class FirefoxUtils {
/**
* 设置Firefox路径,返回FirefoxDriver
*
* @param path
* Firefox路径
* @return FirefoxDriver
*/
public static FirefoxDriver getFirefoxDriver(String path) {
File pathToBinary = new File(path);
FirefoxBinary firefoxBinary = new FirefoxBinary(pathToBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();
System.setProperty("webdriver.gecko.driver", "E:\\资源\\selenium-java-3.1.0\\geckodriver.exe");
return new FirefoxDriver(firefoxBinary, firefoxProfile);
}
/**
* 设置默认Firefox路径,返回FirefoxDriver
*
* @return FirefoxDriver
*/
public static FirefoxDriver getFirefoxDriver() {
return FirefoxUtils.getFirefoxDriver("D:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
}
}
TestFirefoxDriver源码如下:
package test;
import org.openqa.selenium.WebDriver;
import utils.FirefoxUtils;
/**
*
* @author dehua.ye
*
*/
public class TestFirefoxDriver {
public static void main(String[] args) {
WebDriver driver = FirefoxUtils.getFirefoxDriver();
driver.get("https://www.baidu.com");
String url = driver.getCurrentUrl();
System.out.println(url);
driver.close();
}
}
Step 4:开始测试
运行main方法测试,如果能正常打开Firefox浏览器,并且访问百度官网,同时console中输出了百度网址,则成功。
注意
(1)指定firefox安装路径
FirefoxDriver类提供了好几种构造方法,如果不指定任何参数,那么会在默认的路径中去寻找firefox,如果没有找到则会报错: org.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH. Make sure firefox is installed. 由于我的windows7系统在安装firefox时更换安装路径为D盘,所以我这里指定了firefox路径: D:\Program Files (x86)\Mozilla Firefox\firefox.exe
(2)指定geckodriver
如果没有配置geckodriver,那么会报错: java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases
所以,这里我先下载了最新版的geckodriver,然后在java代码中设置了 webdriver.gecko.driver 。
参考资料