Selenium二次封装(Java版本)

废话太多招人烦!话不多说撸代码。

这些都是我在写自动化的时候自己封装的和一些在网上找的,有不足之处请大家谅解

对浏览器操作的封装

public class Browser_operation {
    public static WebDriver driver;
    //打开浏览器
    public static WebDriver openBrowser(String browser) {
        if (browser.equals("firefox")) {
            System.setProperty("webdriver.firefox.bin", "D:\\Mozilla Firefox\\firefox.exe");//浏览器安装路径,我这里使用的是火狐浏览器
            driver = new FirefoxDriver();
        } else {
            System.out.println("你的浏览器出错了" + browser);
        }
        return driver;
    }

    // 刷新浏览器
    public static void refresh() {
        driver.navigate().refresh();
    }

    // 浏览器前进
    public static void forward() {
        driver.navigate().forward();
    }

    // 浏览器后退
    public static void back() {
        driver.navigate().back();
    }

    //关闭浏览器  关闭窗口不关闭后台进程
    public static void close() {
        driver.close();
    }

    //关闭浏览器  关闭窗口 关闭后台进程
    public static void quit() {
        driver.quit();
    }

    //浏览器最大化
    public static void maximize() {
        driver.manage().window().maximize();
    }

    //设置浏览器大小
    public static void manage(int x, int y) {
        Dimension dimension = new Dimension(x, y);
        driver.manage().window().setSize(dimension);
    }

    //获取当前页面URL
    public static void getUrl(int x, int y) {
        driver.getCurrentUrl();
    }

    //获取当前页面Title
    public static void getTitle(int x, int y) {
        driver.getTitle();
    }
  }

封装元素加载等待时间

public class WebElementUtil extends Browser_operation {

    //findElement
    public static WebElement findElement(final By by) {
        WebElement webelement = null;
        try {
            webelement = new WebDriverWait(driver, 20).until(new ExpectedCondition<WebElement>() {
                public WebElement apply(WebDriver webDriver) {
                    return driver.findElement(by);
                }
            });
        } catch (Exception e) {
            System.out.println("元素:" + by + "查找超时!!!");
            e.printStackTrace();
        }
        return webelement;
    }

    //findElements
    public static List<WebElement> findElements(final By by) {
        List<WebElement> WebElement = null;
        try {
            WebElement = new WebDriverWait(driver, 20).until(new ExpectedCondition<List<WebElement>>() {
                @NullableDecl
                public List<WebElement> apply(WebDriver webDriver) {
                    return driver.findElements(by);
                }
            });
        } catch (Exception e) {
            System.out.println("元素:" + by + "查找超时!!!");
            e.printStackTrace();
        }
        return WebElement;
    }
}

对iframe切换控制权封装

public class Switch_Iframe extends Browser_operation {
    final static LoggerControler log = LoggerControler.getLogger(Switch_Iframe.class);
    //根据iframe id 定位
    public static void switchToFrameById(String iframeId) {
        driver.switchTo().frame(iframeId);
    }

    //根据iframe name 定位
    public static void switchToFrameByName(String iframeName) {
        driver.switchTo().frame(iframeName);
    }

    //根据iframe 下标 定位 0代表该页面的第一个<iframe>标签
    public static void switchToFrameByIndex(int index) {
        driver.switchTo().frame(index);
    }

    //用定位器定位 By.xpth("")等
    public static void switchToIframeByElement(By by) {
        WebElement webElement = driver.findElement(by);
        driver.switchTo().frame(webElement);
    }


    //返回上一层iframe
    public static void switchToParentIframe() {
        driver.switchTo().parentFrame();
    }

    //返回最外层
    public static void switchToDefaultContentIframe() {
        driver.switchTo().defaultContent();
    }

}

对元素操作动作的封装

public class ActionsUtil extends Browser_operation {

    //点击动作click
    public static void click(By by) {
        WebElementUtil.findElement(by).click();
    }

    //文本框输入
    public static void sendText(By by, String text) {
        WebElementUtil.findElement(by).sendKeys(text);
    }

    //清空文本框
    public static void clear(By by) {
        WebElementUtil.findElement(by).clear();
    }

    //获取文本框中内容
    public static String getText(By by) {
        String text = WebElementUtil.findElement(by).getText();
        return text;
    }

    //获取多个内容
    public static ArrayList getTexts(By by) {
        ArrayList arrayList = new ArrayList();
        List<WebElement> list = WebElementUtil.findElements(by);
        for (int i = 0; i < list.size(); i++) {
            String text = list.get(i).getText();
            arrayList.add(text);
        }
        return arrayList;
    }

    //鼠标双击
    public static void doubleClick(WebDriver driver, By by) {
        Actions actions = new Actions(driver);
        WebElement ement = WebElementUtil.findElement(by);
        actions.doubleClick(ement).perform();
    }

}

鼠标操作封装

public class Mouse_Operation extends Browser_operation {

    // 鼠标悬浮指定元素并点击
    public static void moveToElementBy(By by) {
        Actions actions = new Actions(driver);
        WebElement webElement = WebElementUtil.findElement(by);
        actions.moveToElement(webElement).perform();
    }


    // 鼠标右键点击
    public static void RightClickWebElement(By by) {
        Actions actions = new Actions(driver);
        WebElement webElement = WebElementUtil.findElement(by);
        actions.contextClick(webElement).perform();
    }

    // 鼠标双击
    public static void DoubleClickWebElement(By by) {
        Actions actions = new Actions(driver);
        WebElement webElement = WebElementUtil.findElement(by);
        actions.doubleClick(webElement).perform();
    }
}

生成随机数工具类

public class RandomNum {

    //生成一个n为随机数
    public static long getNumRandom(int length) {
        //随机数乘以10^n次方
        long num = 0;
        num = (long) (Math.random() * Math.pow(10, length));
        return num;
    }

    //如输出一个范围之间的随机数
    public static long getNumRandom1(int min, int max) {

        long num = 0;
        Random random = new Random();
        num = random.nextInt(max - min + 1) + min;
        return num;
    }

    //生成随机数字和字母
    public static String getStringRandom(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(10) % 2 == 0 ? "char" : "num";
            if ("char".equals(charOrNum)) {
                int temp = random.nextInt(10) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equals(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

截图封装

public class ScreenShotsUtil extends Browser_operation {

    public static void screenShot(WebDriver driver) {
        String dir_name = "screenshot";
        if (!(new File(dir_name).isDirectory())) {
            new File(dir_name).mkdir();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        try {
            File source_file = (((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE));// 执行截屏
            FileUtils.copyFile(source_file, new File(dir_name + File.separator + time + ".png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 截图命名为当前时间保存桌面
    public static void takeScreenshotByNow() throws IOException {
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
        String time = sdf.format(new Date());
        String file = "C:\\Users\\Administrator\\Desktop\\bug截图\\" + time + ".png";
        FileUtils.copyFile(srcFile, new File(file));
    }

    // 截图重命名保存至桌面
    public static void takeScreenshotByName(String name) throws IOException {
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        String file = "C:\\Users\\Administrator\\Desktop\\bug截图\\" + name + ".png";
        FileUtils.copyFile(srcFile, new File(file));
    }

}

获取table表格工具类

public class TableUtil {
    public static void traverseTable(By by) {
        //获取table表格
        WebElement webElement = WebElementUtil.findElement(by);
        List<WebElement> rows = webElement.findElements(By.tagName("tr"));
        for (WebElement row : rows) {
            List<WebElement> cols = row.findElements(By.tagName("td"));
            for (WebElement col : cols) {
                System.out.print(col.getText() + "\t");
            }
            System.out.println("table表格错误");
        }
    }
  }

上传文件

public class UploadFileUtil extends Browser_operation {

    /**
     * 上传文件
     * filePath  文件路劲
     */
    public static void uploadFile(By locator, String filePath) {
        driver.findElement(locator).sendKeys(filePath);
    }
}

读取Excel表格

public class ExcelUtil {
    //新方法(使用中)---------------------------------------------------------------------------------------------
    public List<String[]> rosolveFile(InputStream is, String suffix, int startRow) throws IOException, FileNotFoundException {
        Workbook xssfWorkbook = null;
        if ("xls".equals(suffix)) {
            xssfWorkbook = new HSSFWorkbook(is);//HSSFWorkbook为Excel的文档对象
        } else if ("xlsx".equals(suffix)) {
            xssfWorkbook = new XSSFWorkbook(is);
        }
        //表格中的sheet
        Sheet xssfSheet = xssfWorkbook.getSheetAt(0); //Sheet 为excel的表单
        if (xssfSheet == null) {
            return null;
        }
        ArrayList<String[]> list = new ArrayList<String[]>();
        int lastRowNum = xssfSheet.getLastRowNum();
        for (int rowNum = startRow; rowNum <= lastRowNum; rowNum++) {
            if (xssfSheet.getRow(rowNum) != null) {
                Row xssfRow = xssfSheet.getRow(rowNum);// Row excel的行
                short firstCellNum = xssfRow.getFirstCellNum();
                short lastCellNum = xssfRow.getLastCellNum();
                if (firstCellNum != lastCellNum) {
                    String[] values = new String[lastCellNum];
                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                        Cell xssfCell = xssfRow.getCell(cellNum);//Cell excel的格子单元
                        if (xssfCell == null) {
                            values[cellNum] = "";
                        } else {
                            values[cellNum] = parseExcel(xssfCell);
                        }
                    }
                    list.add(values);
                }
            }
        }
        return list;
    }

    //判断每一个单元格里的内容类型
    public String parseExcel(Cell cell) {
        String result = null;

        switch (cell.getCellType()) {

            case HSSFCell.CELL_TYPE_NUMERIC:// 判断单元格的值是否为数字类型

                if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
                    SimpleDateFormat sdf = null;
                    if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
                            .getBuiltinFormat("h:mm")) {
                        sdf = new SimpleDateFormat("HH:mm");
                    } else {// 日期
                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                    }
                    Date date = cell.getDateCellValue();
                    result = sdf.format(date);
                } else if (cell.getCellStyle().getDataFormat() == 58) {
                    // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
					/*yyyy年m月d日----->31
					yyyy-MM-dd-----	14
					yyyy年m月-------	57
					m月d日  ----------58
					HH:mm-----------20
					h时mm分  -------	32*/

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    double value = cell.getNumericCellValue();
                    Date date = DateUtil
                            .getJavaDate(value);
                    result = sdf.format(date);
                } else {
                    double value = cell.getNumericCellValue();
                    CellStyle style = cell.getCellStyle();
                    DecimalFormat format = new DecimalFormat();
                    String temp = style.getDataFormatString();
                    // 单元格设置成常规
                    if (temp.equals("General")) {
                        format.applyPattern("#");
                    }
                    result = format.format(value);
                }
                break;
            case HSSFCell.CELL_TYPE_STRING:// 判断单元格的值是否为String类型
                result = cell.getRichStringCellValue().toString();
                break;
            case HSSFCell.CELL_TYPE_BLANK://判断单元格的值是否为布尔类型
                result = "";
            default:
                result = "";
                break;
        }
        return result;
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值