欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用seleniumIDE来实现自动化网页测试(mac+java/python)

程序员文章站 2022-03-22 14:09:26
...

简介

Selenium 是用于测试 Web 应用程序用户界面 (UI) 的常用框架。
在网上可以找到很多firefox和selenium相结合的教程,但是由于版本的配套问题,实在是费了很大精力,(并不是说在浏览器上随便一装就能行,不论是Firefox还是chrome,都会出现版本对应的问题,但是在新版firefox+新版selenium还是有问题),所以我选择了使用chrome的这条路,但是由于我用的又是mac,所以找教程真的花了不少时间,下面是我的一些经历。

首先,检查chrome的版本,我的是65,所以也要去下载对应的ChromeDriver(这个是chrome的驱动,程序通过调用这个来控制chrome)。

版本对应表:
https://blog.csdn.net/huilan_same/article/details/51896672

mac下放在usr/local/bin下 或者 在写java程序的时候按如下声明位置

System.setProperty(“webdriver.chrome.driver”,”/Users/wing/Downloads/chromedriver”);

当然我不是一点点自己写的,chrome上早有人做好了录制and导出的插件,我们直接用就可以了,首先进入谷歌商店(需*):

https://chrome.google.com/webstore/category/extensions?utm_source=chrome-ntp-icon

然后搜索seleniumIDE,第一个发绿光的katalon就是我们想要的,安装,打开之后,点击record(录制),然后进行一系列的网页操作,之后停止录制,再点play(重放),就可以重复之前的操作。

导出后的代码如下:

package hw3;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class UntitledTestCase {

    private WebDriver driver;
    private String baseUrl;
    private boolean acceptNextAlert = true;
    private StringBuffer verificationErrors = new StringBuffer();

    @Before
    public void setUp() throws Exception {
        System.setProperty("webdriver.chrome.driver", "/Users/wuchen/Downloads/chromedriver");
        driver = new ChromeDriver();
        baseUrl = "https://www.katalon.com/";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    @Test
    public void test233() throws Exception {
        driver.get("https://www.baidu.com");
    }

    @After
    public void tearDown() throws Exception {
        driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }

    private boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

    private boolean isAlertPresent() {
        try {
            driver.switchTo().alert();
            return true;
        } catch (NoAlertPresentException e) {
            return false;
        }
    }

    private String closeAlertAndGetItsText() {
        try {
            Alert alert = driver.switchTo().alert();
            String alertText = alert.getText();
            if (acceptNextAlert) {
                alert.accept();
            } else {
                alert.dismiss();
            }
            return alertText;
        } finally {
            acceptNextAlert = true;
        }
    }
}
  • 实验要求:编写Selenium Java WebDriver程序,测试input.xlsx表格中的学号和网页中的git地址的对应关系是否正确。

添加了读取xlsx类的java代码:

读取类(别人写好的类,截取了读取xlsx的部分,十分感谢):

package hw3;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class read {

    public static Object[][] getTestData(String filePath) throws FileNotFoundException, IOException {
        File excelFile = new File(filePath);
        /*
         * 判断给定文件的类型; 1.如果是xls的问价那类型就创建XSSFWorkBook ; 2.如果是xlsx的文件类型就创建HSSFWorkBook ;
         */

        String xls = filePath.substring(filePath.indexOf('.'));
        //System.out.println("传入文件的后缀是:" + xls + " ;");
        if (xls.equals(".xls")) {

        } 
        else if (xls.equals(".xlsx")) {
            XSSFWorkbook wbxlsx = new XSSFWorkbook(new FileInputStream(excelFile));
            XSSFSheet sheet = wbxlsx.getSheetAt(0);

            int rowcount = sheet.getLastRowNum() - sheet.getFirstRowNum();
            List<Object[]> list = new ArrayList<Object[]>();
            // System.out.println("---------该sheet总共有 :" + rowcount + " ;");
            Row row;
            Cell cell;
            for (int i = 0; i < rowcount + 1; i++) {
                row = sheet.getRow(i);
                /*
                 * System.out.println("当前行是:" + (row.getRowNum() + 1) + " ;当前行的第一个单元格是:" +
                 * row.getFirstCellNum() + " ; 当前前的最后一个单元格是:" + row.getLastCellNum() + "; ");
                 */
                Object[] obj = new Object[row.getLastCellNum()];
                // System.out.println("obj 数组的长度是 :" + obj.length + " ;");
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    cell = row.getCell(j);
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_STRING:
                        obj[j] = cell.getRichStringCellValue().getString();
                        /*
                         * System.out.print(cell.getRichStringCellValue(). getString());
                         * System.out.print("|");
                         */
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        if (DateUtil.isCellDateFormatted(cell)) {
                            obj[j] = cell.getDateCellValue();
                            // System.out.print(String.valueOf(cell.getDateCellValue()));
                        } else {
                            obj[j] = cell.getNumericCellValue();
                            // System.out.print(cell.getNumericCellValue());
                        }
                        // System.out.print("|");
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        obj[j] = cell.getBooleanCellValue();
                        /*
                         * System.out.print(cell.getBooleanCellValue()); System.out.print("|");
                         */
                        break;
                    default:
                    }

                }
                list.add(obj);
                System.out.println();
            }
            // System.out.println("list.size()===" + list.size());
            Object[][] object = new Object[list.size()][];
            for (int i = 0; i < object.length; i++) {
                object[i] = list.get(i);
            }
            return object;
        } else {
            System.out.println("指定的文件不是excle文件!");
        }
        return null;
    }
}
package hw3;

import java.util.regex.Pattern;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class UntitledTestCase {

    private WebDriver driver;
    private String baseUrl;
    private boolean acceptNextAlert = true;
    private StringBuffer verificationErrors = new StringBuffer();

    @Before
    public void setUp() throws Exception {
        System.setProperty("webdriver.chrome.driver", "/Users/wuchen/Downloads/chromedriver");
        driver = new ChromeDriver();
        baseUrl = "https://www.katalon.com/";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    @Test
    public void test233() throws Exception {

        String filePathxlsx = "/Users/wuchen/Downloads/input.xlsx";
        // Object [][] objxls =DP_Demo.getTestData(filePathxls);
        Object[][] objxlsx = read.getTestData(filePathxlsx);

        for (int i = 0; i < objxlsx.length; i++) {
            //System.out.println(objxlsx[i][0] + " " + objxlsx[i][1]);

            String name = objxlsx[i][0].toString();

            BigDecimal b = new BigDecimal(name);
            name = b.toPlainString();
            if(objxlsx[i][1] == null) {
                System.out.println("你啥也没写啊" + name);
                continue;
            }
            String url = objxlsx[i][1].toString();

            driver.get("https://psych.liebes.top/st");
            driver.findElement(By.id("username")).click();
            driver.findElement(By.id("username")).clear();
            driver.findElement(By.id("username")).sendKeys(name);
            driver.findElement(By.id("password")).clear();
            driver.findElement(By.id("password")).sendKeys(name.substring(name.length()-6));
            driver.findElement(By.id("submitButton")).click();
            if(url.equals(driver.findElement(By.xpath("//p")).getText() ) ) {
                //成功
                System.out.println(name + " 's " + url+ " is ok");
            }
            else {
                System.out.println(name + " 's " + url+ " is wrong");
            }
            //assertEquals(url, driver.findElement(By.xpath("//p")).getText());

        }

        /*
         * Object[] obj1 = objxlsx[0];
         * 
         * for (int i = 0; i < obj1.length; i++) { System.out.print("[" + obj1[i] +
         * "] "); }
         */





    }

    @After
    public void tearDown() throws Exception {
        driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }

    private boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

    private boolean isAlertPresent() {
        try {
            driver.switchTo().alert();
            return true;
        } catch (NoAlertPresentException e) {
            return false;
        }
    }

    private String closeAlertAndGetItsText() {
        try {
            Alert alert = driver.switchTo().alert();
            String alertText = alert.getText();
            if (acceptNextAlert) {
                alert.accept();
            } else {
                alert.dismiss();
            }
            return alertText;
        } finally {
            acceptNextAlert = true;
        }
    }
}

完成测试。
遇到的问题:
* 有的人的学号在input中是用科学计数法表示的,得先处理成一般数字再取。
* 有的人的input中没有填写url。。。
* 有的人填的url不对。。。

测试结果:
使用seleniumIDE来实现自动化网页测试(mac+java/python)

还是python的精简:

from openpyxl import load_workbook
from selenium import webdriver

def read_from_xlsx(path):
    workbook = load_workbook(path)
    sheets = workbook.sheetnames  # 从名称获取sheet
    booksheet = workbook[sheets[0]]
    rows = booksheet.rows
    #迭代所有的行
    line = []
    for row in rows:
        line.append( [col.value for col in row] )
    #通过坐标读取值
    #cell_11 = booksheet.cell('a1').value
    #cell_11 = booksheet.cell(row=1, column=1).value
    return line

def main():
    pass

if __name__ == '__main__':
    main()
    book = read_from_xlsx("/users/wuchen/downloads/input.xlsx")
    driver = webdriver.Chrome()
    for row in book:
        s1,s2 = str(int(row[0])),str(row[1])
        driver.get('https://psych.liebes.top/st')
        driver.find_element_by_id("username").click()
        driver.find_element_by_id("username").clear()
        driver.find_element_by_id("username").send_keys(s1)
        driver.find_element_by_id("password").clear()
        driver.find_element_by_id("password").send_keys(s1[-6:])
        driver.find_element_by_id("submitButton").click()
        if driver.find_element_by_xpath("//p").text == s2:
            print(s1,'is ok')
        else:
            print(s1,"not ok")
相关标签: 自动化测试