4_Selenium框架封装

摘要:
˃firefoxhttp://www.cnblogs.com/lizitest/2解析XML文件代码packagecom.selenium。工具importjava.io。文件importorg.dom4j。文件importorg.dom4j。DocumentException;importorg.dom4j。要素导入组织.dom4j.io。SAXReader;/***@作者Chestnut测试*使用SAX解析XML文件**/publicclassParseXML{privateDocumentdocument;/***构造函数*在创建对象时加载XML文件*/publicParseXML{this.loadXML;}/***加载XML文件*/publicvoidloadXML{//创建新文件Filefile=newFile;如果{//SAXReaderAXReadersaxReader=newSAXReader();请尝试{document=saxReader.read;}在dom4j包中捕获{e.printStackTrace();}}否则{System.out.println;}}/***获取text*/publicStringgetSingleNodeText{Elementelement=document.selectSingleNode;if(element!

1 封装WebDriver

  • 封装代码编写
package com.selenium.test;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class InitWebDriver {

    public static WebDriver myDriver(String browser) {
        
        WebDriver driver = null;
        
        if ("firefox".equals(browser.toLowerCase())) {
            
            //启动本机firefox
            ProfilesIni allProfiles = new ProfilesIni();
            FirefoxProfile profile = allProfiles.getProfile("default");
            //启动浏览器
            driver = new FirefoxDriver(profile);
            driver.manage().window().maximize();
            
        }else if ("ie".equals(browser.toLowerCase())) {
            
            //关闭保护模式
            DesiredCapabilities capability = new DesiredCapabilities();
            capability.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);    
            capability.setCapability("ignoreProtectedModeSettings",true);
            //指定驱动位置,并加载驱动
            System.setProperty("webdriver.ie.driver", "drivers/IEDriverServer.exe");
            driver = new InternetExplorerDriver(capability);
            driver.manage().window().maximize();
            
        } else if ("chrome".equals(browser.toLowerCase())) {
            
            //指定驱动位置,并加载驱动
            System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
            driver = new ChromeDriver();
            driver.manage().window().maximize();
            
        }else{
            
            System.out.println("浏览器指定错误!!!");
        }
        return driver;
        
    } 

}
  • 测试代码编写
package com.selenium.test;

import org.openqa.selenium.WebDriver;

public class InitWebDriverTest {

    public static void main(String[] args) {
        
        WebDriver myBrowser = InitWebDriver.myDriver("firefox");
        myBrowser.navigate().to("http://www.cnblogs.com/lizitest/");
        
//        WebDriver myBrowser = InitWebDriver.myDriver("ie");
//        myBrowser.navigate().to("http://www.cnblogs.com/lizitest/");
//        
//        WebDriver myBrowser = InitWebDriver.myDriver("chrome");
//        myBrowser.navigate().to("http://www.cnblogs.com/lizitest/");

    }

}

 2 使用配置文件

  •  加载jar包

4_Selenium框架封装第1张

  • 编写config文件
<?xml version="1.0" encoding="UTF-8"?>
<chuanke>
    <browser>firefox</browser>
    <url>http://www.cnblogs.com/lizitest/</url>
    <waitTime>2</waitTime>
</chuanke>
  • 解析XML文件代码
package com.selenium.tool;

import java.io.File;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


/**
 * @author 栗子测试
 * 使用SAX(Simple APIs for XML,也即XML简单应用程序接口)解析XML文件
 *
 */
public class ParseXML {
    
    private Document document;
    
    /**
     * 构造函数
     * 在新建对象的同时加载XML文件
     */
    public ParseXML(String filePath){
        this.loadXML(filePath);
    }
    
    /**
     * 加载XML文件
     */
    public void loadXML(String filePath){
        
        //新建文件
        File file = new File(filePath);
        
        if(file.exists()){
            //dom4j包中SAXReader
            SAXReader saxReader = new SAXReader();
            try {
                
                document = saxReader.read(file);
                
            } catch (DocumentException e) {
                
                e.printStackTrace();
            }
        }else{
            
            System.out.println("XML文件不存在");
        }
    }

    
    /**
     * 获取节点上的文本
     */
    public String getSingleNodeText(String nodePath){
        
        Element element = (Element) document.selectSingleNode(nodePath);
        
        if(element != null){
            
            return element.getTextTrim();
            
        }else{
            
            System.out.println("节点不存在!");
            return null;
        }
    }
    
}
  • 解析config文件
package com.selenium.util;

import com.selenium.tool.ParseXML;

public interface Config {

    public static ParseXML xml = new ParseXML(".\config\config.xml");
    public static String browser = xml.getSingleNodeText("//browser");
    public static String url = xml.getSingleNodeText("//url");
    public static String waitTime = xml.getSingleNodeText("//waitTime");
}
  • 测试代码
package com.selenium.util;

import org.openqa.selenium.WebDriver;

public class InitWebDriverTest2 {

    public static void main(String[] args) {
        
        WebDriver myBrowser = InitWebDriver.myDriver(Config.browser);
        myBrowser.navigate().to(Config.url);

    }

}

 3 xpath及控件识别

  •  控件识别
package com.selenium.util;

import java.util.List;
import java.util.Set;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.NoSuchWindowException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;

public class MyBrowser {

    WebDriver driver =null;
    
    public MyBrowser(String browsr) {
        this.driver = InitWebDriver.myDriver(browsr);
    }
    
    //页面导航
    public void navigateTo(String url) {
        driver.navigate().to(url);
    }
    
    //输入框
    public WebElement webEdit(String xpath){
        
        try{
            WebElement webEdit = driver.findElement(By.xpath(xpath));
            webEdit.clear();
            return webEdit;
        }catch(NoSuchElementException e){
            System.out.println("输入框不存在!");
            return null;
        }catch (ElementNotVisibleException e) {
            System.out.println("XPath匹配多个输入框!");
            return null;
        }
        
    }
    
    //按钮
    public WebElement webButton(String xpath){
        
        try{
            WebElement webButton = driver.findElement(By.xpath(xpath));
            return webButton;
        }catch(NoSuchElementException e){
            System.out.println("按钮不存在!");
            return null;
        }catch (ElementNotVisibleException e) {
            System.out.println("XPath匹配多个按钮!");
            return null;
        }
        
    }
    
    //链接
    public WebElement link(String xpath) {
        
        try{
            WebElement link = driver.findElement(By.xpath(xpath));
            return link;
        }catch(NoSuchElementException e){
            System.out.println("链接按钮不存在!");
            return null;
        }catch (ElementNotVisibleException e) {
            System.out.println("XPath匹配多个链接!");
            return null;
        }
        
    }

    //悬停
    public void hover(String xpath) {
        
        try{
            WebElement element = driver.findElement(By.xpath(xpath));
            Actions action = new Actions(driver); 
            action.moveToElement(element).perform();
        }catch(NoSuchElementException e){
            System.out.println("悬停对象不存在!");
        }catch (ElementNotVisibleException e) {
            System.out.println("XPath匹配多个悬停对象!");
        }
        
    }
    
    //窗口切换
    public void switchToWindow(String title) {
        
        try {
            String currentHandle = driver.getWindowHandle();
            Set<String> handles = driver.getWindowHandles();
            
            for (String handle : handles){
                    if(handle.equals(currentHandle)){
                            continue;
                    }else{
                            driver.switchTo().window(handle);
                            if (driver.getTitle().contains(title)){ break; }
                            else{ continue; }
                    }
            }
        } catch (NoSuchWindowException e) {
            System.out.println("没有找到窗口!");
        }

    }
    
    //单选按钮
    public List<WebElement> webRadioGroup(String xpath) {

        try{
            List<WebElement> radios = driver.findElements(By.xpath(xpath));    //定位所有单选按钮
            return radios;
        }catch(IndexOutOfBoundsException e){
            System.out.println("单选按钮不存在!");
            return null;
        }catch (ElementNotVisibleException e) {
            System.out.println("XPath匹配多个单选按钮!");
            return null;
        }
    }
    
    //多选按钮
    public List<WebElement> WebCheckBox(String xpath){
        
        try{
            List<WebElement> checkboxs = driver.findElements(By.xpath(xpath));    //定位所有多选按钮
            return checkboxs;
        }catch(IndexOutOfBoundsException e){
            System.out.println("多选按钮不存在!");
            return null;
        }catch (ElementNotVisibleException e) {
            System.out.println("XPath匹配多个多选按钮!");
            return null;
        }
    }
    
    //下拉框
    public Select webList(String xpath){
        
        try{
            WebElement selectElement = driver.findElement(By.xpath(xpath));    //先定位下拉框
            Select select = new Select(selectElement);
            return select;
        }catch(NoSuchElementException e){
            System.out.println("下拉框不存在!");
            return null;
        }catch (ElementNotVisibleException e) {
            System.out.println("XPath匹配多个下拉框!");
            return null;
        }
    }

    //上传文件(input)
    public WebElement upLoadFile(String xpath){
        
        try{
            WebElement file = driver.findElement(By.xpath(xpath));
            return file;
        }catch(NoSuchElementException e){
            System.out.println("上传文件控件不存在!");
            return null;
        }catch (ElementNotVisibleException e) {
            System.out.println("XPath匹配多个上传文件控件!");
            return null;
        }
    }
    
    //JS
    public void  executeJS(String jsString){
        JavascriptExecutor js = (JavascriptExecutor)driver;
        js.executeScript(jsString);    
    }

     //iframe
    public void switchToIframe(String xpath){
        WebElement iframe = driver.findElement(By.xpath(xpath));
        driver.switchTo().frame(iframe);
    }
    
    //弹出框
    public Alert switchToAlert(){
        
        Alert alert = driver.switchTo().alert();    //切换到弹出窗
        return alert;
    }
    
}
  • xpath维护(部分)
package com.seleniu.pages;

//接口只是一个抽象方法声明和静态不能被修改的数据的集合
public interface BaiduHome {
    
    public String LINK_LOGIN = "//div[@id='u1']/a[text()='登录']";
    public String WEBEDIT_USERNAME = "//input[@id='TANGRAM__PSP_8__userName']";
    public String WEBEDIT_PASSWORD = "//input[@id='TANGRAM__PSP_8__password']";
    public String WEBBUTTON_USERNAME = "//input[@id='TANGRAM__PSP_8__submit']";
    public String LINK_USERNAME = "//a[@id='s_username_top']/span";
    
}
  • 测试代码
package com.selenium.util;

import com.seleniu.pages.BaiduAccountSetting;
import com.seleniu.pages.BaiduHome;
import com.seleniu.pages.BaiduPersonalSetting;

public class MyBrowserTest implements BaiduHome,BaiduAccountSetting,BaiduPersonalSetting{

    public static void main(String[] args) throws InterruptedException {
        
        MyBrowser myBrowser = new MyBrowser(Config.browser);
        myBrowser.navigateTo(Config.url);
        myBrowser.link(LOGIN).click();
        
        Thread.sleep(3000);
        
        //登录
        myBrowser.webEdit(USERNAME).sendKeys("栗子测试");
        myBrowser.webEdit(PASSWORD).sendKeys("2472471982");
        myBrowser.webButton(WEBBUTTON_USERNAME).click();
        
        Thread.sleep(3000);
        //悬停
        myBrowser.hover(LINK_USERNAME);

        //账号设置
        myBrowser.link(ACCOUNTSETTING).click();
        myBrowser.switchToWindow(AS_TITLE);
                
        //修改资料
        myBrowser.link(MODIFYDATA).click();
        myBrowser.switchToWindow(PS_TITLE);
        //基本资料
        myBrowser.webRadioGroup(GENDER).get(0).click();
        myBrowser.link(DIV_BLOOD).click();
        myBrowser.link(LINK_BLOOD).click();
        myBrowser.webButton(SAVE).click();
        //详细资料
        myBrowser.link(DETAILEINFO).click();
        myBrowser.WebCheckBox(CHARACTER).get(5).click();
        myBrowser.webButton(SAVE).click();
        
        //其他
        myBrowser.webList(OTHER).selectByVisibleText("XX");
        myBrowser.upLoadFile(OTHER).sendKeys("XXX");
        myBrowser.executeJS("XXX");
        myBrowser.switchToIframe("XXX");
        myBrowser.switchToAlert().accept();
        
    }

}
  •  目录结构

 4_Selenium框架封装第2张

栗子测试

  • 所有文章均为原创,是栗子测试所有人员智慧的结晶,如有转载请标明出处
  • 如果您在阅读之后觉得有所收获,请点击右下角推荐
  • QQ:2472471982,欢迎大家前来咨询和探讨(暗号:栗子测试)

 
 

免责声明:文章转载自《4_Selenium框架封装》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇可以查看硬盘目录大小的工具TabControl TabPage添加关闭按钮下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

asp.net mvc+EF 递归生成树结构返回json

0、数据表结构,主要属性有:Id、parentId(父节Id)、Text、Url……等等。 1、新建一个树结构MenuModels 1 public class MenuModels 2 { 3 private int _id; 4 private string _text; 5...

java 实现基于opencv全景图合成

因项目需要,自己做了demo,从中学习很多,所以分享出来,希望有这方面需求的少走一些弯路,opencv怎么安装网上教程多多,这里不加详细说明,我安装的opencv-3.3.0  如上图所示,找到相应的jar包,这里讲一下如何这个jar如何导入Maven仓库 mvn install:install-file -Dfile=D:opencv-3.0.0ope...

RestTemplate 工具类以及拦截器配置打印调用日志

RestTemplate工具类 /** * RestTemplate 远程调用工具类 */ public class RestTemplateUtil { private static final RestTemplate restTemplate = SpringContextHolder.getBean(RestTemplate.class...

遇到double 数目过大,转String变成科学计数法

问题:   java中,当double数目过大,转出String时,变成了科学记数法的表示。 总结:   1.项目的存储用的是mysql,mysql的类型和java类型之间存在映射关系,以前关注不多。现在总结一下:    类型名称 显示长度 数据库类型 JAVA类型 JDBC类型索引(int) 描述             VARCHAR L+...

使用spring-rabbit测试RabbitMQ消息确认(发送确认,接收确认)

1、首先是rabbitmq的配置文件: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-in...

MyBatis基础总结

1.1什么是MyBatis MyBatis(前身是iBatis)是一个支持普通SQL查询、存储过程以及高级映射的持久层框架, 它消除了几乎所有的JDBC代码和参数的手动设置以及对结果集的检索,并使用简单的XML或注解进行配置和原始映射, 用以将接口和Java的POJO(Plain Old Java Object,普通Java对象)映射成数据库中的记录,使得...