1、安装jdk
2、安装eclipse
3、安装selenium
由于使用的是开发语言是java,因此需要安装java版的selenium包。下载地址:http://pan.baidu.com/s/1hq6mebE,下载的版本为:selenium-java-2.53.0。下载完成后,进行解压,得到如下目录:
下载完jar包后,在已经创建的项目上右键,选择properties,选择java Build Path,选择导入额外的jar包,详情如下:
导入jar包后:
4、安装浏览器驱动
Firefox--selenium原生支持,不需要安装浏览器驱动
IE--需要安装浏览器驱动
chrome--需要安装浏览器驱动
以IE为例:
首先下载IEDriverServer.exe,将该驱动防止到IE浏览器安装路径下:C:\Program Files (x86)\Internet Explorer
配置系统路径path,配置如下:
5、接下来编写一个简单的程序,测试环境搭建是否通过
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.chrome.*;
import org.openqa.selenium.ie.*;
public class WebDriverLearn {
WebDriver driver = new InternetExplorerDriver();
driver.get("https://www.baidu.com/");
}
}
运行:
报错如下:
Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.ie.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver. The latest version can be downloaded from http://selenium-release.storage.googleapis.com/index.html
at com.google.common.base.Preconditions.checkState(Preconditions.java:199)
at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:109)
at org.openqa.selenium.ie.InternetExplorerDriverService.access$0(InternetExplorerDriverService.java:1)
at org.openqa.selenium.ie.InternetExplorerDriverService$Builder.findDefaultExecutable(InternetExplorerDriverService.java:167)
at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:296)
at org.openqa.selenium.ie.InternetExplorerDriver.setupService(InternetExplorerDriver.java:251)
at org.openqa.selenium.ie.InternetExplorerDriver.<init>(InternetExplorerDriver.java:172)
at org.openqa.selenium.ie.InternetExplorerDriver.<init>(InternetExplorerDriver.java:146)
at WebDriverLearn.main(WebDriverLearn.java:27)
报错原因:
找不到IE浏览器相关文件,需要设置下system property。利用System.setProperty方法来添加路径,代码更新如下:
import org.openqa.selenium.*;
import org.openqa.selenium.ie.*;
public class WebDriverLearn {
public static void main(String[] args) {
System.setProperty("webdriver.ie.driver", "C:/Program Files (x86)/Internet Explorer/IEDriverServer.exe"); //指定IE浏览器安装路径
WebDriver driver = new InternetExplorerDriver();
driver.get("https://www.baidu.com/");
}
}
运行本段代码,能够顺利打开IE浏览器。
注意:本文使用的selenium-java-2.53.0.jar,IE浏览器为IE9.
selenium和不同的浏览器,会有不同的兼容性问题,需要选择正确的相互兼容的selenium和浏览器。目前只找到selenium-java-2.53.0.jar和IE9兼容.