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

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

流柯      

目录
相关文章
|
20天前
|
安全 Java 数据安全/隐私保护
|
20天前
|
搜索推荐 Java
Java的面向对象特性主要包括封装、继承和多态
【4月更文挑战第5天】Java的面向对象特性主要包括封装、继承和多态
15 3
|
22天前
|
Web App开发 前端开发 Java
《手把手教你》系列技巧篇(九)-java+ selenium自动化测试-元素定位大法之By name(详细教程)
【4月更文挑战第1天】 这篇教程介绍了如何使用Selenium Webdriver通过name属性来定位网页元素,作为系列教程的一部分,之前讲解了id定位,后续还会有其他六种定位方法。文中以百度搜索为例,详细说明了定位搜索框(name=&quot;wd&quot;)并输入关键词“北京宏哥”的步骤,包括手动操作流程、编写自动化脚本以及代码实现。此外,还提供了查看和理解Selenium源码的方法,强调了`open implementation`选项用于查看方法的具体实现。整个过程旨在帮助读者学习Selenium的元素定位,并实践自动化测试。
41 0
|
18天前
|
前端开发 Java 测试技术
《手把手教你》系列技巧篇(十二)-java+ selenium自动化测试-元素定位大法之By link text(详细教程)
【4月更文挑战第4天】本文介绍了link text在自动化测试中的应用。Link text是指网页中链接的文字描述,点击可跳转至其他页面。文章列举了8种常用的定位方法,其中着重讲解了link text定位,并通过实例展示了如何使用Java代码实现点击百度首页的“奥运奖牌榜 最新排名”链接,进入相应页面。如果link text不准确,则无法定位到元素,这说明linkText是精准匹配,而非模糊匹配。文章还提到了partial link text作为link text的模糊匹配版本,将在后续内容中介绍。
37 4
|
17天前
|
XML 前端开发 Java
《手把手教你》系列技巧篇(十四)-java+ selenium自动化测试-元素定位大法之By xpath上卷(详细教程)
【4月更文挑战第6天】按宏哥计划,本文继续介绍WebDriver关于元素定位大法,这篇介绍定位倒数二个方法:By xpath。xpath 的定位方法, 非常强大。使用这种方法几乎可以定位到页面上的任意元素。xpath 是XML Path的简称, 由于HTML文档本身就是一个标准的XML页面,所以我们可以使用Xpath 的用法来定位页面元素。XPath 是XML 和Path的缩写,主要用于xml文档中选择文档中节点。基于XML树状文档结构,XPath语言可以用在整棵树中寻找指定的节点。
43 0
|
1天前
|
Web App开发 数据采集 Java
《手把手教你》系列技巧篇(三十)-java+ selenium自动化测试- Actions的相关操作下篇(详解教程)
【4月更文挑战第22天】本文介绍了在测试过程中可能会用到的两个功能:Actions类中的拖拽操作和划取字段操作。拖拽操作包括基本讲解、项目实战、代码设计和参考代码,涉及到鼠标按住元素并将其拖动到另一个元素上或指定位置。划取字段操作则介绍了如何在一段文字中随机选取一部分,包括项目实战、代码设计和参考代码。此外,文章还提到了滑动验证的实现,并提供了相关的代码示例。
10 2
|
6天前
|
前端开发 JavaScript Java
《手把手教你》系列技巧篇(二十五)-java+ selenium自动化测试-FluentWait(详细教程)
【4月更文挑战第17天】其实今天介绍也讲解的也是一种等待的方法,有些童鞋或者小伙伴们会问宏哥,这也是一种等待方法,为什么不在上一篇文章中竹筒倒豆子一股脑的全部说完,反而又在这里单独写了一篇。那是因为这个比较重要,所以宏哥专门为她量身定制了一篇。FluentWait是Selenium中功能强大的一种等待方式,翻译成中文是流畅等待的意思。在介绍FluentWait之前,我们来讨论下为什么需要设置等待,我们前面介绍了隐式等待和显式等待。
28 3
|
8天前
|
Java 测试技术 定位技术
《手把手教你》系列技巧篇(二十三)-java+ selenium自动化测试-webdriver处理浏览器多窗口切换下卷(详细教程)
【4月更文挑战第15天】本文介绍了如何使用Selenium进行浏览器窗口切换以操作不同页面元素。首先,获取浏览器窗口句柄有两种方法:获取所有窗口句柄的集合和获取当前窗口句柄。然后,通过`switchTo().window()`方法切换到目标窗口句柄。在项目实战部分,给出了一个示例,展示了在百度首页、新闻页面和地图页面之间切换并输入文字的操作。最后,文章还探讨了在某些情况下可能出现的问题,并提供了一个简单的本地HTML页面示例来演示窗口切换的正确操作。
34 0
|
11天前
|
前端开发 JavaScript Java
《手把手教你》系列技巧篇(十九)-java+ selenium自动化测试-元素定位大法之By css下卷(详细教程)
【4月更文挑战第11天】按计划今天宏哥继续讲解css的定位元素的方法。但是今天最后一种宏哥介绍给大家,了解就可以了,因为实际中很少用。
35 2
|
13天前
|
前端开发 JavaScript Java
《手把手教你》系列技巧篇(十八)-java+ selenium自动化测试-元素定位大法之By css中卷(详细教程)
【4月更文挑战第10天】本文主要介绍了CSS定位元素的几种方法,包括ID属性值定位、其他属性值定位和使用属性值的一部分定位。作者提供了示例代码,展示了如何使用这些方法在Java+Selenium自动化测试中定位网页元素。通过CSS选择器,可以更精确地找到页面上的特定元素,如输入框、按钮等,并进行相应的操作,如输入文本、点击等。文章还提供了实际运行代码后的控制台输出和浏览器动作的示例。
49 0

热门文章

最新文章