4_Selenium框架封装

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包

  • 编写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();
        
    }

}
  •  目录结构

 

栗子测试

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

 
 

转载于:https://www.cnblogs.com/lizitest/p/5137407.html

### 封装Selenium框架以简化自动化测试代码 #### 使用面向对象编程进行封装 通过创建特定于应用程序的对象模型来表示网页及其组件,可以使测试脚本更加直观易读。对于每一个页面或功能模块都可以定义对应的类,在这些类内部实现具体的操作逻辑。 ```python from selenium import webdriver class BasePage(object): """基础页面类""" def __init__(self, driver): self.driver = driver class LoginPage(BasePage): """登录页面的具体操作""" # 定义页面元素定位器 _username_locator = (By.CSS_SELECTOR,'#idInput') _password_locator = (By.CSS_SELECTOR,'#pwdInput') _confirm_button_locator = (By.CSS_SELECTOR,'#loginBtn') @property def username(self): return self.driver.find_element(*LoginPage._username_locator) @property def password(self): return self.driver.find_element(*LoginPage._password_locator) @property def confirm_button(self): return self.driver.find_element(*LoginPage._confirm_button_locator) def login(self, user_name, pass_word): self.username.clear() self.username.send_keys(user_name) self.password.clear() self.password.send_keys(pass_word) self.confirm_button.click() ``` 此部分代码展示了如何利用Python中的`@property`装饰器以及继承机制来构建一个更易于维护和扩展的结构[^1]。 #### 利用描述符特性进一步优化 除了上述方法外还可以采用描述符模式对页面上的各个UI控件做一层抽象处理,从而达到更高的灵活性与可重用度: ```python import weakref class ElementDescriptor: """用于描述单个HTML元素的行为特征""" def __init__(self, by, value=None, desc=''): self.by = by self.value = value self.desc = desc self.data = {} def __get__(self, obj, cls=None): if not hasattr(obj, '_webdriver'): raise AttributeError('No WebDriver instance found.') element_id = f'{obj.__class__.__name__}.{self.desc}' if element_id not in self.data: self.data[element_id] = obj._webdriver.find_element(by=self.by, value=self.value) return self.data[element_id] def __set__(self, obj, val): elem = self.__get__(obj) elem.clear() elem.send_keys(val) class PageObjectWithDescriptors(PageObjectBase): username = ElementDescriptor(By.CSS_SELECTOR,'#idInput', '用户名输入框') password = ElementDescriptor(By.CSS_SELECTOR,'#pwdInput','密码输入框') submit_btn = ElementDescriptor(By.CSS_SELECTOR,'#submitBtn','提交按钮') def perform_login(self, usr, pwd): self.username = usr self.password = pwd self.submit_btn.click() # 实际使用时只需要实例化并调用相应的方法即可完成交互动作而无需关心底层细节。 page = PageObjectWithDescriptors(driver=webdriver.Chrome()) page.perform_login('test_user', 'secret_password') ``` 这段代码片段说明了怎样借助Python内置的数据描述符协议让页面对象属性具备动态获取实际DOM节点的能力,并且支持赋值语句直接触发相应的键盘鼠标事件模拟[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值