码迷,mamicode.com
首页 > Web开发 > 详细

selenium操作web自动化小小封装体验

时间:2019-06-20 21:22:40      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:nal   public   action   webdriver   return   orm   出现   mat   keyevent   

元素判断封装

import lombok.extern.log4j.Log4j;
import org.openqa.selenium.By;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

/**
 * @author liwen
 * 用来读取配置文件
 */
@Log4j
public class ObjectMap {

    private static Properties properties = null;

    public  ObjectMap(String filename) {
        properties = new Properties();
        try {
            FileInputStream in = new FileInputStream((filename));
            properties.load(in);
            in.close();
        } catch (Exception e) {
            System.out.println("找不到文件:" + filename);
            e.printStackTrace();
        }
    }

    /**
     * 处理元素定位
     *
     * @param name
     * @return
     * @throws Exception
     */
    public  By getLocateor(String name) throws Exception {
        String locator = ObjectMap.properties.getProperty(name);
        String locatortype = locator.split(">>")[0].toLowerCase();
        String locatorvalue = locator.split(">>")[1];
        locatorvalue = new String(locatorvalue.getBytes("ISO-8859-1"), "UTF-8");
        if ("cssselector".equals(locatortype)) {
            return By.cssSelector(locatorvalue);
        } else if ("id".equals(locatortype)) {
            return By.id(locatorvalue);
        } else if ("name".equals(locatortype)) {
            return By.name(locatorvalue);
        } else if ("classname".equals(locatortype)) {
            return By.className(locatorvalue);
        } else if ("tagname".equals(locatortype)) {
            return By.tagName(locatorvalue);
        } else if ("linktext".equals(locatortype)) {
            return By.linkText(locatorvalue);
        } else if ("parialllinktest".equals(locatortype)) {
            return By.partialLinkText(locatorvalue);
        } else if ("xpath".equals(locatortype)) {
            return By.xpath(locatorvalue);
        } else {
            throw new Exception("该元素没有找到");
        }
    }
}

元素文件

cn.index.signinBtn=id>>kw
cn.index.cart=id>>su
jd.closeBtn=id>>closeBtn
jd.input=xpath>>//*[@id="search-box-app"]/div/div[1]/input
jd.search=xpath>>//*[@id="search-box-app"]/div/div[1]/button/i

简单操作封装


//封装键盘操作的方法
public class KeyBoardUtil {
    //按Ctrl+F5
    public static void refresh(WebDriver driver)
    {
        Actions ctrl=new Actions(driver);
        ctrl.keyDown(Keys.CONTROL).perform();
        try{
            pressKeyEvent(KeyEvent.VK_F5);
        }catch (AWTException e)
        {
            e.printStackTrace();
        }
        ctrl.keyUp(Keys.CONTROL).perform();
    }
    //按物理键
    public static void pressKeyEvent(int keycode) throws AWTException{
        Robot robot=new Robot();
        //robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyPress(keycode);
    }
    //鼠标左键按下和释放
    public static void MouseClickAndRelease(WebDriver driver){
        Actions action=new Actions(driver);
        action.clickAndHold().perform();
        try{
            Thread.sleep(1000);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        action.release().perform();
        try{
            Thread.sleep(1000);
        }catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    // 鼠标悬浮
    public static void perform(WebDriver driver,WebElement element) {
        Actions action = new Actions(driver);
        action.moveToElement(element).perform();

    }

智能等待封装


import com.google.common.base.Function;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.List;

/**封装各种等待方法*/
public class WaitUtil {

    //显示等待多少秒
    public static void sleep(long seconds) {
        try {
            Thread.sleep(seconds);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //显示等待页面标题是否出现了某个关键字
    public static void waitWebElementTitle(WebDriver driver, String title) {
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until((ExpectedConditions.titleContains(title)));

    }

    //显示等待页面元素的出现
    public static void waitWebElement(WebDriver driver, By by) {
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.presenceOfElementLocated(by));

    }

    //自定义等待某个元素显示
    public static WebElement waitForElementVisible(WebDriver driver, final By locator, long timeOutInSeconds) {
        Function<WebDriver, WebElement> waitFn = new Function<WebDriver, WebElement>() {
            @Override
            public WebElement apply(WebDriver driver) {
                try {
                    WebElement element = driver.findElement(locator);
                    if (!element.isDisplayed()) {
                        KeyBoardUtil.refresh(driver);
                        WaitUtil.sleep(1000);
                    }
                    if (element.isDisplayed()) {
                        return element;
                    }
                } catch (Exception e) {
                    return null;
                }
                return null;
            }
        };
        WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
        return wait.until(waitFn);
    }

    //自定义某个元素列表是否出现
    public static List<WebElement> waitForElementVisiblelist(WebDriver driver, final By locator, long timeOutInSeconds) {
        Function<WebDriver, List<WebElement>> waitFn = new Function<WebDriver, List<WebElement>>() {
            @Override
            public List<WebElement> apply(WebDriver driver) {
                try {
                    List<WebElement> elementList = driver.findElements(locator);
                    if (elementList.isEmpty()) {
                        KeyBoardUtil.refresh(driver);
                        WaitUtil.sleep(1000);
                    }
                    if (!elementList.isEmpty()) {
                        return elementList;
                    }
                } catch (Exception e) {
                    return null;
                }
                return null;
            }
        };
        WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
        return wait.until(waitFn);
    }

    public static Boolean waitForElementPresent(WebDriver driver, final By locator, long timeOutInSeconds) {
        Function<WebDriver, Boolean> waitFn = new Function<WebDriver, Boolean>() {
            @Override
            public Boolean apply(WebDriver driver) {
                try {
                    WebElement element = driver.findElement(locator);
                    if (!element.isDisplayed()) {
                        KeyBoardUtil.refresh(driver);
                        WaitUtil.sleep(1000);
                    }
                    if (element.isDisplayed()) {
                        return true;
                    }
                } catch (Exception e) {
                    return false;
                }
                return false;
            }
        };
        WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
        return wait.until(waitFn);
    }

断言封装

测试对象封装

import jdth.pcautomation.util.ObjectMap;
import jdth.pcautomation.util.WaitUtil;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

/**
 * @author liwen
 * @Title: thop
 * @Description:
 * @date 2019/6/18 / 19:45
 */
public class TopTh {

    public TopTh() {
        objectMap = new ObjectMap("e:\\test\\loginIndex.properties");
    }

    private WebElement element = null;
    private ObjectMap objectMap;

    public WebElement getSiginBtn(WebDriver driver) throws Exception {
        WaitUtil.waitWebElement(driver, objectMap.getLocateor("cn.index.signinBtn"));
        element = driver.findElement(objectMap.getLocateor("cn.index.signinBtn"));
        return element;
    }

    public WebElement getSiginkw(WebDriver driver) throws Exception {
        WaitUtil.waitWebElement(driver, objectMap.getLocateor("cn.index.cart"));
        element = driver.findElement(objectMap.getLocateor("cn.index.cart"));
        return element;
    }
}

测试运行

import lombok.extern.log4j.Log4j;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

/**
 * @author liwen
 * @Title: PcAoutTest
 * @Description: PC自动化 dome
 * @date 2019/6/18 / 14:10
 */
@Log4j
public class PcAoutTest {

    public String url = "https://www.baidu.com/";
    WebDriver driver = null;

    @BeforeClass
    public WebDriver init() {
        //IE启动程序路径
        System.setProperty("webdriver.chrome.driver", "D:\\javaspaces\\driver\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        return driver;
    }

    @Test

    public void getbaidu() throws Exception {
//        WebDriver driver = new ChromeDriver();
        driver.get(url);
        log.info("调试");
        new TopTh().getSiginBtn(driver).sendKeys("测试");
        new TopTh().getSiginkw(driver).click();
        Thread.sleep(2000);
//        driver.quit();
    }
        }

selenium操作web自动化小小封装体验

标签:nal   public   action   webdriver   return   orm   出现   mat   keyevent   

原文地址:https://blog.51cto.com/357712148/2411718

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!