Java Selenium封装--RemoteWebDriver

简介: 1 package com.selenium.driver; 2 import java.io.File; 3 import java.io.IOException; 4 import java.
  1 package com.selenium.driver;
  2 import java.io.File;
  3 import java.io.IOException;
  4 import java.net.URL;
  5 import java.util.HashMap;
  6 import java.util.Map;
  7 import java.util.Set;
  8 import java.util.regex.Matcher;
  9 import java.util.regex.Pattern;
 10 import org.apache.commons.io.FileUtils;
 11 import org.openqa.selenium.Alert;
 12 import org.openqa.selenium.Capabilities;
 13 import org.openqa.selenium.Cookie;
 14 import org.openqa.selenium.JavascriptExecutor;
 15 import org.openqa.selenium.NoSuchElementException;
 16 import org.openqa.selenium.OutputType;
 17 import org.openqa.selenium.TakesScreenshot;
 18 import org.openqa.selenium.WebDriver;
 19 import org.openqa.selenium.WebElement;
 20 import org.openqa.selenium.remote.Augmenter;
 21 import org.openqa.selenium.remote.RemoteWebDriver;
 22 import org.openqa.selenium.remote.RemoteWebElement;
 23 public class JSWebDriver{
 24     private RemoteWebDriver wd = null;
 25     private JavascriptExecutor jse = null;
 26     
 27     public JSWebDriver(URL remoteAddress, Capabilities desiredCapabilities) {
 28         wd = new RemoteWebDriver(remoteAddress, desiredCapabilities);
 29     }
 30     
 31     ///
 32     ///浏览器url导航
 33     ///
 34     public void goTo(String url){
 35         wd.get(url);
 36     }    
 37     
 38     ///
 39     ///浏览器退出
 40     ///
 41     public void quit(){
 42         wd.quit();
 43     }
 44 
 45     ///
 46     ///浏览器后退
 47     ///
 48     public void back(){
 49         wd.navigate().back();
 50     }
 51 
 52     ///
 53     ///浏览器前进
 54     ///
 55     public void forward(){
 56         wd.navigate().forward();
 57     }
 58     
 59     ///
 60     ///浏览器刷新
 61     ///
 62     public void refresh(){
 63         wd.navigate().refresh();
 64     }
 65     
 66     ///
 67     ///切换到新浏览器窗口;按照title、url、index;支持正则匹配
 68     ///
 69     public void switchToWindow(String by, String value, String...match) throws Exception{
 70         String currenthandle = wd.getWindowHandle();
 71         Set<String> handles = wd.getWindowHandles();
 72         int currentIndex = -1;
 73         String searchString = "";
 74         for(String handle : handles){
 75             currentIndex += 1;
 76             if(handle.equals(currenthandle)){
 77                 continue;
 78             }else{                
 79                 wd.switchTo().window(handle);
 80                 if (match.length == 1 && match[0].equals("regex")){                    
 81                     if (by.equals("title")){
 82                         searchString = wd.getTitle();
 83                     }else if (by.equals("url")){
 84                         searchString = wd.getCurrentUrl();
 85                     }    
 86                     Pattern pattern = Pattern.compile(value);
 87                     Matcher matcher = pattern.matcher(searchString);
 88                     if(matcher.find()){
 89                         return;
 90                     }
 91                 }else{
 92                     if (by.equals("title")){
 93                         searchString = wd.getTitle();
 94                     }else if (by.equals("url")){
 95                         searchString = wd.getCurrentUrl();
 96                     }else if (by.equals("index")){
 97                         searchString = Integer.toString(currentIndex);
 98                     }
 99                     if(searchString.equals(value)){
100                         return;
101                     }
102                 }
103             }
104         }
105         Exception e = new Exception("Swtich Window Failed, Please Make Sure The Locator Was Right.");
106         throw e;
107     }
108     
109     ///
110     ///JS弹框确认
111     ///
112     public void clickAlertSure(){
113         Alert alert = wd.switchTo().alert();
114         alert.accept();
115     }
116     
117     ///
118     ///JS弹框取消
119     ///
120     public void clickAlertDismiss()
121     {
122         Alert alert = wd.switchTo().alert();
123         alert.dismiss();
124     }
125     
126     ///
127     ///设置prompt弹框内容
128     ///
129     public void setPromptMessage(String parameter){
130         Alert alert = wd.switchTo().alert();
131         alert.sendKeys(parameter);
132     }
133     
134     ///
135     ///获取JS弹框内容
136     ///
137     public String getPromptMessage(){
138         Alert alert = wd.switchTo().alert();
139         return alert.getText();
140     }    
141     
142     ///
143     ///切换到Frame窗口;先定位到iframe元素
144     ///
145     public void switchToFrame(JSWebElement jselement){        
146         wd.switchTo().frame(jselement.getNativeWebElement());
147     }
148 
149     ///
150     ///执行JS脚本
151     ///
152     public void executeScript(String parameter){
153         JavascriptExecutor js = getJSE();
154         js.executeScript(parameter);
155     }
156 
157     ///
158     ///获取指定cookie
159     ///
160     public String getCookie(String name){
161         Cookie cookie=wd.manage().getCookieNamed(name);
162         if (cookie == null){ return "null"; }
163         return cookie.getValue();
164     }
165     
166     ///
167     ///获取所有cookie
168     ///
169     public Map<String, String> getCookies(){
170         Map<String, String> newCookies = new HashMap<String, String>();
171         Set<Cookie> cookies= wd.manage().getCookies();
172         for (Cookie cookie : cookies){
173             newCookies.put(cookie.getName(), cookie.getValue());
174         }
175         return newCookies;
176     }
177     
178     ///
179     ///截取屏幕
180     ///
181     public void getScreen(String filepath){
182         WebDriver augmentedDriver = new Augmenter().augment(this.wd); 
183         TakesScreenshot ts = (TakesScreenshot) augmentedDriver;
184         File screenShotFile = ts.getScreenshotAs(OutputType.FILE); 
185         try { 
186             FileUtils.copyFile (screenShotFile, new File(filepath)); 
187         }catch (IOException e){ 
188             e.printStackTrace(); 
189         } 
190     }
191 
192     ///
193     ///获取title
194     ///
195     public String getTitle(){
196         return wd.getTitle();
197     }    
198 
199     ///
200     ///获取url
201     ///
202     public String getUrl(){
203         return wd.getCurrentUrl();
204     }
205     
206     ///
207     ///获取HTML源码
208     ///
209     public String getSource(){
210         try {
211             Thread.sleep(500);
212         } catch (InterruptedException e) {
213             e.printStackTrace();
214         }
215         return wd.getPageSource();
216     }
217     
218     ///
219     ///滚动页面到指定位置
220     ///
221     public void scroll(String x, String y){
222         if (x.equals("left")){
223             x = "0";
224         }else if (x.equals("right")){
225             x = "document.body.scrollWidth";
226         }else if (x.equals("middle")){
227             x = "document.body.scrollWidth/2";
228         }
229         if (y.equals("top")){
230             y = "0";
231         }else if (y.equals("buttom")){
232             y = "document.body.scrollHeight";
233         }else if (y.equals("middle")){
234             y = "document.body.scrollHeight/2";
235         }
236         this.executeScript(String.format("scroll(%s,%s);", x, y));
237     }
238     
239     ///
240     ///最大化浏览器
241     ///
242     public void maximize(){
243         wd.manage().window().maximize();
244     }
245     
246     public JSWebElement findElementById(String using) {
247         try {
248             return new JSWebElement((RemoteWebElement)wd.findElementById(using));
249         }catch (NoSuchElementException e){
250             return new JSWebElement();
251         }
252     }
253     
254     public JSWebElement findElementByCssSelector(String using) {
255         try {
256             return new JSWebElement((RemoteWebElement)wd.findElementByCssSelector(using));
257         }catch (NoSuchElementException e){
258             return new JSWebElement();
259         }
260     }
261     
262     public JSWebElement findElementByXPath(String using) {
263         try {
264             return new JSWebElement((RemoteWebElement)wd.findElementByXPath(using));
265         }catch (NoSuchElementException e){
266             return new JSWebElement();
267         }
268     }
269 
270     public JSWebElement findElementByLinkText(String using) {
271         try {
272             return new JSWebElement((RemoteWebElement)wd.findElementByLinkText(using));
273         }catch (NoSuchElementException e){
274             return new JSWebElement();
275         }
276     }
277     
278     public JSWebElement findElementByDom(String using) {
279         try {
280             JavascriptExecutor js = this.getJSE();
281             WebElement we = (WebElement)js.executeScript(String.format("return %s", using));            
282             return new JSWebElement((RemoteWebElement)we);
283         }catch (NoSuchElementException e){
284             return new JSWebElement();
285         }
286     }
287     
288     ///
289     ///获取原生的RemoteWebdriver对象
290     ///
291     public RemoteWebDriver getNativeWebDriver(){
292         return this.wd;
293     }
294     
295     private JavascriptExecutor getJSE(){
296         if (this.jse == null){
297             this.jse = (JavascriptExecutor) this.wd;                
298         }        
299         return jse;
300     }
301 }

 


img_42a4adae4716d0e15c3eeaabfd040044.png

注:转载需注明出处及作者。

流柯      

目录
相关文章
|
1天前
|
安全 Java 数据安全/隐私保护
Java基础之类封装、继承、多态
Java基础的封装、继承和多态是OOP的核心。封装通过访问控制(如private)隐藏类的内部细节,提供公共接口供外部交互。例如,`Person`类封装`name`和`age`,通过`getName()`和`setAge()`方法访问。继承允许子类(如`Dog`)继承父类(如`Animal`)的属性和方法,并可扩展或覆盖。多态使得父类引用可指向子类对象,调用方法时根据实际对象类型执行,如不同动物的`makeSound()`。接口实现多态提供了一种定义行为而不必关心实现的方式。向上转型(子类→父类)安全且默认,而向下转型(父类→子类)需类型检查以避免异常。
6 1
|
1天前
|
Java 数据安全/隐私保护
Java基础之类封装、继承、多态
Java基础之类封装、继承、多态
8 2
|
1天前
|
XML Web App开发 测试技术
《手把手教你》系列基础篇(七十八)-java+ selenium自动化测试-框架设计基础-TestNG依赖测试- 中篇(详解教程)
【6月更文挑战第19天】本文介绍了使用TestNG框架配置XML文件来管理测试用例的分组和依赖关系。
12 2
|
2天前
|
Java 测试技术 Python
《手把手教你》系列基础篇(七十七)-java+ selenium自动化测试-框架设计基础-TestNG依赖测试- 上篇(详解教程)
【6月更文挑战第18天】TestNG是一个Java测试框架,它允许在测试方法间定义执行顺序和依赖关系。当不指定依赖时,TestNG默认按方法名首字母排序执行。`@Test`注解的`dependsOnMethods`属性用于指定方法依赖,如`test1`依赖`test4`,则实际执行顺序为`test4`、`test2`、`test3`、`test1`。如果依赖的方法失败,后续依赖的方法将被跳过。此外,`dependsOnGroups`属性通过组名指定依赖,方便管理多个相关测试方法。通过`groups`定义方法所属组,然后在其他方法中用`dependsOnGroups`引用这些组。
19 5
|
2天前
|
Java 数据安全/隐私保护 开发者
Java是一种完全支持面向对象编程的语言,其面向对象特性包括封装、继承、多态和抽象等
【6月更文挑战第18天】**面向对象编程(OOP)通过对象封装状态和行为,实现问题域的抽象。Java全面支持OOP,核心特性包括**: - **封装**:保护数据安全,隐藏内部细节。 - **继承**:子类继承父类属性和行为,促进代码重用。 - **多态**:一个接口多种实现,增强灵活性和扩展性。 - **抽象**:通过接口和抽象类抽离共性,简化复杂性。 **Java的OOP便于理解和解决复杂系统问题。**
13 3
|
2天前
|
安全 Java 开发者
类与对象:Java中的封装、继承与多态
Java面向对象三大特性:封装(隐藏对象细节,增强安全与复用),继承(代码复用与扩展,如Dog继承Animal),多态(统一接口,不同实现,如Playable接口的Piano和Guitar)。通过示例展示了如何在实践中应用这些概念。【6月更文挑战第16天】
12 2
|
3天前
|
存储 测试技术 数据安全/隐私保护
《手把手教你》系列基础篇(七十六)-java+ selenium自动化测试-框架设计基础-TestNG实现DDT - 下篇(详解教程)
【6月更文挑战第17天】本文是一篇关于使用Selenium和TestNG进行数据驱动测试的教程。作者宏哥通过实例展示了如何处理多个用户登录场景。
37 0
|
4天前
|
安全 Java
Java 面向对象之旅:封装——让代码更加“接地气”的秘诀。
【6月更文挑战第16天】**Java面向对象的封装秘籍:**将数据和操作打包成类,如`Student`和`Car`,隐藏内部详情,只通过`get/set`方法交互。封装提升代码清晰度,便于管理和保护安全性,就像整理工具箱,让每个功能一目了然,操作自如。
|
4天前
|
安全 Java 数据安全/隐私保护
一探 Java 封装究竟:为何它让代码更加“高大上”?
【6月更文挑战第16天】Java中的封装如城堡般迷人,它确保数据安全(如`UserInfo`类的私有属性),增强代码结构(如`Order`类的操作封装),并提升复用性与扩展性(如`Shape`类的抽象设计)。封装是打造高质量、易维护代码的关键,让代码既安全又高效。
|
4天前
|
Java 数据安全/隐私保护
Java 封装:打破传统,创新你的编程思维!
【6月更文挑战第16天】Java中的封装是将数据和操作数据的方法封装在类中,隐藏内部细节,通过公共接口交互。这样保证了数据安全,降低了耦合度,便于验证(如`Shape`类中构造函数的类型检查)和控制(如`setType`方法中添加额外操作)。封装使代码更清晰、可维护,鼓励创新编程思维。