溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

selenium操作web自動(dòng)化小小封裝體驗(yàn)

發(fā)布時(shí)間:2020-06-26 00:33:19 來源:網(wǎng)絡(luò) 閱讀:523 作者:知止內(nèi)明 欄目:編程語言

元素判斷封裝


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

簡(jiǎn)單操作封裝


//封裝鍵盤操作的方法
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);
    }
    //鼠標(biāo)左鍵按下和釋放
    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();
        }

    }

    // 鼠標(biāo)懸浮
    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();
        }
    }

    //顯示等待頁(yè)面標(biāo)題是否出現(xiàn)了某個(gè)關(guān)鍵字
    public static void waitWebElementTitle(WebDriver driver, String title) {
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until((ExpectedConditions.titleContains(title)));

    }

    //顯示等待頁(yè)面元素的出現(xiàn)
    public static void waitWebElement(WebDriver driver, By by) {
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.presenceOfElementLocated(by));

    }

    //自定義等待某個(gè)元素顯示
    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);
    }

    //自定義某個(gè)元素列表是否出現(xiàn)
    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);
    }

斷言封裝

測(cè)試對(duì)象封裝

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;
    }
}

測(cè)試運(yùn)行

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自動(dòng)化 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啟動(dòng)程序路徑
        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("調(diào)試");
        new TopTh().getSiginBtn(driver).sendKeys("測(cè)試");
        new TopTh().getSiginkw(driver).click();
        Thread.sleep(2000);
//        driver.quit();
    }
        }
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI