Java Selenium框架的开发和优化教程-01
1.背景
在我给我们公司写的爬虫框架和UI自动化测试框架中,都使用到了Java+Selenium,而随着框架功能体积的增大,很自然地需要对Selenium进行进一步的封装和优化,以应对愈发复杂的需求。
下面我把这两个项目中,对于selenium的使用、封装和优化的方式抽出来写成一个Maven的demo项目,进行详细介绍,供大家参考。
2.项目一览
2.1 项目结构
这个demo的Maven项目是我精简过的,所以非常简单,结构如下图:
核心代码:
Selenium操作页面的流程是:初始化浏览器的driver,启动浏览器 -> 定位界面的元素 -> 操作界面元素。
所以我把这三大步分布封装成图中的三个类:
- UiActions - 对UI基础操作的封装
- UiContext - 对浏览器上下文的封装
- UiFinder - 对UI元素查找器的封装
在下文中会对核心代码有详细的介绍。
具体实现
这里我以百度为例,简单演示了封装好的框架是如何操作浏览器并执行百度搜索的过程。
浏览器驱动
浏览器驱动我使用的是Chrome Driver,放在resources路径下是方便框架直接进行调用。
2.2 集成浏览器驱动WebDriver
首先,需要下载WebDriver。各浏览器下载地址:
Firefox浏览器驱动:geckodriver
Chrome浏览器驱动:chromedriver taobao备用地址
IE浏览器驱动:IEDriverServer
Edge浏览器驱动:MicrosoftWebDriver
Opera浏览器驱动:operadriver
PhantomJS浏览器驱动:phantomjs
打开taobao备用地址,我下载的是74.0.3729.6版本(当然你们也可以选择更新的版本),如下图:
然后下载chromedriver_win32.zip并解压,如下图:
然后将其中的chromedriver.exe放到项目的resource\WebDriver路径下即可。
2.3 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javaseleniumdemo</groupId>
<artifactId>javaseleniumdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<!--可以引入日志 @Slf4j注解-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<!--用于截屏保存文件-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
</project>
3.代码示例
3.1 对浏览器上下文的封装
UiContext这个类即为对浏览器上下文的封装,它需要包括初始化浏览器、设置浏览器特性、获取浏览器上下文以及关闭浏览器释放资源等功能,代码如下:
package com.javaseleniumdemo.core;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.WebDriverWait;
/**
* @author Joy
*/
class UiContext {
private static UiContext uiContext;
private static WebDriver driver;
private static WebDriverWait wait ;
/**
* description: 获取UI上下文的driver
* @return WebDriver
*/
public static WebDriver getDriver() {
WebDriver d = null;
try {
d = UiContext.getUiContext().driver;
} catch (Exception e