日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Selenium Web 自动化 - 项目实战(三)

發布時間:2025/3/15 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Selenium Web 自动化 - 项目实战(三) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Selenium Web 自動化 - 項目實戰(三)

2016-08-10

目錄

1 關鍵字驅動概述
2 框架更改總覽
3 框架更改詳解
? 3.1 解析新增頁面目錄
? 3.2 解析新增測試用例目錄
? 3.3 解析自動生成代碼
? 3.4 讀取用例excel數據,定位元素,并進行操作
? 3.5 更改SeleniumUtil.java?

源代碼:autotestKeywordDrive.zip

1 關鍵字驅動概述


?返回

關鍵字驅動測試(Keyword-driven testing),也叫做表格驅動測試或者基于行為詞的測試。

關鍵字驅動到底是什么樣的?

見圖3,動作也就是關鍵字,比如你選擇了“點擊”操作,就意味著這步驟會執行一個元素點擊操作。

關鍵子驅動是如何實現的:

問:那么如何定義動作?

答:在框架設計的時候會專門設計一個類,來實現各種“動作”的具體內容。當你在excel中讀取了一個“動作”之后,框架會自動解析這個“動作”背后的事情。在測試框架中這個類的名字叫做:SuperAction.java。

問:如何定義和解析元素定位?

答:見圖2,每個頁面是一個excel,所有元素的定位方式和定位值都保存在里面

問:如何用例存儲?

答:見圖3,一個excel就是一個模塊,然后這個excel文件中一個sheet就是這個模塊中的一條用例

問:Excel文件如何執行測試?

答:excel文件存儲用例,但excel只是文件,如何調用測試入口呢?其實在關鍵字驅動框架中,有一個用例生成類(TestCaseFactoryForSingle.java,TestCaseFactoryForAll.java),它可以遍歷所有excel的所有sheet,生產一條條用例類,見圖6

關鍵字優缺點:

  • 優點:只需要自動化測試人員封裝好相關關鍵字操作,就可以提供給黑盒測試人員用,黑盒測試人員只需要掌握元素定位的方式以及對關鍵字框架的使用即可·條理清晰,很容易上手使用
  • 缺點:需要自動化測試人員花費大量時間提前把關鍵字框架中的操作提前封裝好對于復雜的測試需求,關鍵字框架對于操作的封裝難度較大

2?框架更改總覽


?返回

在原來的框架下更改,如下圖所示

?

圖1 關鍵子驅動與數據驅動比較

3?框架更改詳解


?返回

在原來的框架下更改,如下圖所示

3.1 解析新增頁面目錄

page: 存儲頁面元素的目錄,在此目錄下每個頁面是一個excel,會替換原先框架的com.demo.test.pages包,如圖1所示。

?

圖2 page 元素定位excel

3.2 解析新增測試用例目錄

testcase:存儲測試用例的目錄,每個模塊一個excel文件,每個excel文件中的sheet是一條測試用例,會替換原先框架的com.demo.test.pageshelper包和data目錄,如圖4所示。

圖3 用例Login的Actions

測試用例excel是用于存儲測試用例步驟(如圖4所示)、步驟中涉及的動作(如圖3所示)和測試數據(如圖4所示)等內容,命名規則如下:

  • excel文件命名規則為:“模塊名稱.xlsx”;
  • excel中第二個sheet命名規則:“001_LoginSuccessFunction”來自原框架測試代碼中的部分內容(如圖4所示),也就是省略了“頁面名稱_”:HomePage_和尾部的“_Test”部分:_Test,這兩部分省略的部分在生成代碼的時候會自動添加。

注意:測試用例excel文件sheet“001_LoginSuccessFunction”中的“動作”列(如圖4所示),這列是通過sheet“Actions”中的“動作名稱”列來賦值的:

  • 選擇“動作”列,如下圖所示,整列已經變灰色,表明整列已經被選中。
  • 點擊excel頂部的“數據”tab -> 數據驗證:在數據驗證-設置中選擇驗證條件為:序列并勾選“忽略空值”和“提供下拉箭頭”,點擊來源最右邊的帶箭頭的按鈕,點擊sheet 'Actions',選擇A2到A26(鼠標左鍵先點擊A2不放,然后拖拽至A26),此時注意數據驗證框的變化:=Actions!$A$2:$A$26,點擊回車鍵。
  • ?

    圖4 用例Login的執行步驟

    ?

    圖5 用例excel替換pagehelper類和data excel

    3.3 解析自動生成代碼

    自動生成代碼TestCaseFactoryForSingle.java代碼如下?

    package com.demo.test.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.testng.Assert; import jxl.read.biff.BiffException;/*** * @author xy-incito-wy* @Description 自動生成測試代碼的工具類,生成指定模塊的用例**/ public class TestCaseFactoryForSingle {public static void main(String[] args) {//測試代碼包路徑,如果你的測試代碼目錄不一樣請在這里修改final String caseFolder = "src/com/demo/test/testcases/";//源文件File sourceFile = null;//sheet的名字String sheetName = null;//功能模塊名字String functionName = null;//sheet的號碼int sheetNum = 0;try {@SuppressWarnings("resource")//從控制臺可以輸入Scanner s = new Scanner(System.in); System.out.println("請輸入模塊名稱(不要按回車鍵,輸入完成之后請再按回車鍵):"); functionName = s.nextLine();// 輸入模塊名字 functionName = functionName.replaceFirst(functionName.substring(0, 1),functionName.substring(0, 1).toLowerCase());// 如果包名不存在,就新建File functionPackage = new File(caseFolder + "/" + functionName);if (functionPackage.exists()) {System.out.println(functionName + "包已經存在,自動跳過!");System.out.println("正在生成用例到" + functionName + "包下,請稍等...");} else {functionPackage.mkdir();System.out.println(functionName + "包已創建!");System.out.println("正在生成用例到" + functionName + "包下,請稍等...");}for (int j = 0; j < getSheetNum(getExcelRelativePath(functionName)); j++) { // 根據傳入的模塊文件路徑獲得模塊中sheet數量 也就是用例個數if (j == getSheetNum(getExcelRelativePath(functionName)) - 1) {//如果只有一個sheet的時候(只有Value的情況下),跳出循環不進行自動生成代碼操作,因為沒有可以生成的。break;}try {sheetName = getSheetName(j + 1, getExcelRelativePath(functionName)); // 取得sheetName,由于第一個sheet是values,所以從j+1開始 sheetNum = getSheetNum(getExcelRelativePath(functionName));} catch (BiffException e1) {e1.printStackTrace();}sourceFile = new File(caseFolder+ functionName.toLowerCase()+ File.separator+ functionName.replaceFirst(functionName.substring(0, 1), functionName.substring(0, 1).toUpperCase()) + "Page_" + sheetName+ "_Test.java");// 創建測試用例源碼,指定存放路徑FileWriter writer = new FileWriter(sourceFile);// 生成測試用例代碼的頭文件writer.write("package com.demo.test.testcases."+ functionName+ "; \n"+ "import org.testng.annotations.Test; \n"+ "import com.demo.test.base.BaseParpare; \n "+ "import com.demo.test.utils.SuperAction; \n"+ "public class "+ functionName.replaceFirst(functionName.substring(0, 1), functionName.substring(0, 1).toUpperCase()) + "Page_" + sheetName+ "_Test extends BaseParpare{ \n");// @Test的主體部分,也就是測試用例的方法String firstLetter = sheetName.substring(sheetName.indexOf("_") + 1).substring(0, 1);String others = sheetName.substring(sheetName.indexOf("_") + 1).substring(1);String function = firstLetter.toLowerCase() + others;writer.write("@Test \n"+ " public void"+ " "+ function+ "() { \n"+ "SuperAction.parseExcel(\""+ functionName.replaceFirst(functionName.substring(0, 1), functionName.substring(0, 1).toUpperCase()) + "\",\"" + sheetName+ "\",seleniumUtil);\n" + " }\n");// 代碼結尾大括號writer.write("}");writer.close();}} catch (IOException e) {Assert.fail("IO異常", e);}System.out.println("模塊[" + functionName + "] 的用例已經生成完畢,共計:"+ (sheetNum - 1) + "條,請到" + caseFolder+ functionName.toLowerCase() + "路徑下查閱!");}/*** 獲得excel的相對路徑* * @param 循環模塊名稱的角標* @return 得到對應index的模塊名字*/public static String getExcelRelativePath(String functionName) {String dir = "res/testcase";String path = "";// get file list where the path hasFile file = new File(dir+File.separator+functionName+".xlsx");// get the folder listpath = file.getPath();return path;}/*** 獲得當前excel的sheet數量 - 每個模塊的用例數* * @param filePath* 文件路徑* @return 獲得excel的sheet數量* @throws FileNotFoundException* @throws IOException*/public static int getSheetNum(String filePath)throws FileNotFoundException, IOException {int casesNum = 0;XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(filePath)));casesNum = workbook.getNumberOfSheets();return casesNum;}/*** * @param sheetIndex* sheet的位置* @param filePath* excel文件路徑相對的* @return 返回sheet的名字* @throws BiffException* @throws IOException*/public static String getSheetName(int sheetIndex, String filePath)throws BiffException, IOException {String casesName = "";XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(filePath));casesName = workbook.getSheetName(sheetIndex);return casesName;}} View Code

    TestCaseFactoryForSingle.java這個類,這個類主要是用于生成指定模塊的測試用例,這個類有一個main方法,當你執行之后,會提示你輸入要生成測試代碼的模塊。這里的模塊的名字就是testcase目錄下的excel文件名字(不包含后綴),然后回車,
    此時回到src/com/demo/test/testcases/login包下查看,一條用例生成了 LoginPage_001_LoginSuccessFunction_Test.java,如圖5所示.

    在pom.xml中,添加jar依賴

    <dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.10-FINAL</version></dependency> View Code

    ?

    圖6 自動生成代碼

    3.4 讀取用例excel數據,定位元素,并進行操作

    SuperAction.java代碼如下:

    package com.demo.test.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator;import org.apache.log4j.Logger; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.testng.Assert; /*** * @Description 把Selenium操作的變成關鍵字操作**/ public class SuperAction {public static Logger logger = Logger.getLogger(SuperAction.class.getName());//static String pageFilePath = "res/page/PageElements.xlsx";static String pageFileDir = "res/page/";public static Alert a = null;/*** * @param locateWay 定位方式* @param locateValue 定位的方式的具體值* @return 定位的方式(By)*/public static By getLocateWay(String locateWay,String locateValue){By elementLocator=null;if(locateWay.equalsIgnoreCase("xpath")){elementLocator=By.xpath(locateValue);}else if(locateWay.equalsIgnoreCase("className")){elementLocator=By.className(locateValue);}else if(locateWay.equalsIgnoreCase("id")){elementLocator=By.id(locateValue);}else if(locateWay.equalsIgnoreCase("linktext")){elementLocator=By.linkText(locateValue);}else if(locateWay.equalsIgnoreCase("name")){elementLocator=By.name(locateValue);}else if(locateWay.equalsIgnoreCase("css")){elementLocator=By.cssSelector(locateValue);}else if(locateWay.equalsIgnoreCase("tagname")){elementLocator=By.tagName(locateValue);}else{Assert.fail("你選擇的定位方式:["+locateWay+"] 不被支持!");}return elementLocator;}/*** * @param sheet - 測試用例表中的sheet* @param rowIndex - 測試用例表中的行index* @param locateColumnIndex - 測試用例表中的定位列的index* @return 從page表中 返回定位方式和定位值* @Description 根據testcase中的元素定位列,去取得page頁中的 定位方式和定位值*/public static String[] getPageElementLocator(Sheet sheet,int rowIndex,int locateColumnIndex,String pageName){XSSFWorkbook pageBook = null;//定位方式String elementLocatorWay = null;//定位值String elementLocatorValue = null;//sheet表Sheet pageSheet = null;//page excel路徑String pageFilePath = pageFileDir+pageName+".xlsx";//獲取定位列的值String locator = sheet.getRow(rowIndex).getCell(locateColumnIndex).getStringCellValue();//用.分割開元素定位值String locatorSplit[] = locator.split("\\.");try {pageBook = new XSSFWorkbook(new FileInputStream(new File(pageFilePath)));} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} pageSheet = pageBook.getSheetAt(0); //取得第一個sheetint pageRowNum = pageSheet.getPhysicalNumberOfRows();//獲得這個sheet的實際有效行數for (int j = 0; j < pageRowNum; j++) {//如果獲取到的別名和指定的別名相同,就存儲當前行的定位值和定位方式if(pageSheet.getRow(j).getCell(0).getStringCellValue().equalsIgnoreCase(locatorSplit[1])){elementLocatorWay = pageSheet.getRow(j).getCell(1).getStringCellValue();elementLocatorValue = pageSheet.getRow(j).getCell(2).getStringCellValue();break;}}return new String[]{elementLocatorWay,elementLocatorValue};}/*** @param founction* excel文件的名字* @param caseName* excel中sheet的名字* @param seleniumUtil* 引用seleniumUtil* @Description 讀取excel中每個sheet的操作步驟,進而生成測試用例* */public static void parseExcel(String founction, String caseName, SeleniumUtil seleniumUtil) {FileInputStream filePath = null;XSSFWorkbook workbook = null;String locateSplit[] = null;//頁面sheet中的定位方式和定位值拆解String locator = null;//用例頁面的定位列String file = "res/testcase/" + founction + ".xlsx";try {filePath = new FileInputStream(file);// 讀取功能模塊} catch (FileNotFoundException e) {logger.error("文件:" + file + "不存在");Assert.fail("文件:" + file + "不存在");}try {workbook = new XSSFWorkbook(filePath);} catch (IOException e) {logger.error("IO異常");Assert.fail("IO異常");}/**取得指定的case名字*/Sheet sheet = workbook.getSheet(caseName);/**獲得的實際行數*/int rows = sheet.getPhysicalNumberOfRows(); /** excel中的測試數據*/String testData = null;//獲取首行的單元格數int cellsNumInOneRow = sheet.getRow(0).getPhysicalNumberOfCells();//聲明一個數組存儲列值的角標String column[] = new String[cellsNumInOneRow];//聲明一個迭代器Iterator<Cell> cell = sheet.getRow(0).iterator();int ii =0;while(cell.hasNext()){column[ii]= String.valueOf(cell.next()); ii++;}//定義動作列的角標int actionColumnIndex =0;//定義元素定位列的角標int locateColumnIndex = 0;//定義測試數據列的角標int testDataColumnIndex = 0;//動態獲取這幾個關鍵列所在位置for (int i = 0; i < column.length; i++) {if(column[i].equals("動作")){actionColumnIndex = i;}if(column[i].equals("元素定位")){locateColumnIndex = i;}if(column[i].equals("測試數據")){testDataColumnIndex = i;}}// 循環每行的操作,根據switch來判斷每行的操作是什么,然后轉換成具體的代碼,從第二行開始循環,因為第一行是列的說明數據。 for (int i = 1; i < rows; i++) {logger.info("正在解析excel:["+founction+".xlsx]中的sheet(用例):["+caseName+"]的第"+i+"行步驟...");String action = sheet.getRow(i).getCell(actionColumnIndex).getStringCellValue();Row row = sheet.getRow(i);if (row != null) {switch (action) {case "打開鏈接":testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();seleniumUtil.get(testData);break;case "導航鏈接":testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();seleniumUtil.get(testData);break;case "輸入"://先設置Cell的類型,然后就可以把純數字作為String類型讀進來了 sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue(); //測試數據locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的元素定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]); //找到定位方式、定位值seleniumUtil.type(getLocateWay(locateSplit[0], locateSplit[1]), testData);break;case "點擊":locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);seleniumUtil.click(getLocateWay(locateSplit[0], locateSplit[1]));break;case "暫停"://先設置Cell的類型,然后就可以把純數字作為String類型讀進來了 sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();seleniumUtil.pause(Integer.parseInt(testData));break;case "等待元素"://先設置Cell的類型,然后就可以把純數字作為String類型讀進來了 sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);seleniumUtil.waitForElementToLoad(Integer.parseInt(testData), getLocateWay(locateSplit[0], locateSplit[1]));break;case "查找元素(嘗試3次)"://先設置Cell的類型,然后就可以把純數字作為String類型讀進來了 sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);seleniumUtil.FindElementUtil3TimesTry(Integer.parseInt(testData), getLocateWay(locateSplit[0], locateSplit[1]));break;case "清除":locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);seleniumUtil.clear(getLocateWay(locateSplit[0], locateSplit[1]));break;case "進入iFrame":locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);seleniumUtil.switchFrame(getLocateWay(locateSplit[0], locateSplit[1]));break;case "跳出iFrame":seleniumUtil.outFrame();break;case "選擇下拉列表 - Text"://先設置Cell的類型,然后就可以把純數字作為String類型讀進來了 sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);seleniumUtil.selectByText(getLocateWay(locateSplit[0], locateSplit[1]), testData);break;case "選擇下拉列表 - Index"://先設置Cell的類型,然后就可以把純數字作為String類型讀進來了 sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);seleniumUtil.selectByIndex(getLocateWay(locateSplit[0], locateSplit[1]), Integer.parseInt(testData));break;case "選擇下拉列表 - Value"://先設置Cell的類型,然后就可以把純數字作為String類型讀進來了 sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);seleniumUtil.selectByValue(getLocateWay(locateSplit[0], locateSplit[1]),testData );break; case "檢查文本 - 屬性":testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);String[] Datas = testData.split(",");seleniumUtil.isTextCorrect(seleniumUtil.getAttributeText(getLocateWay(locateSplit[0], locateSplit[1]), Datas[0]),Datas[1]);break;case "獲得網頁標題":testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();seleniumUtil.isTextCorrect(seleniumUtil.getTitle(),testData);break;case "頁面的URL是否正確":testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();seleniumUtil.isTextCorrect(seleniumUtil.getPageURL(), testData);break;case "檢查文本":testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);seleniumUtil.isTextCorrect(seleniumUtil.getText(getLocateWay(locateSplit[0], locateSplit[1])), testData);break;case "進入Tab"://需要改進,第二個窗口的driver問題locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);seleniumUtil.switchNewWindow(getLocateWay(locateSplit[0], locateSplit[1]));break;case "跳出Tab":seleniumUtil.backToOriginalWindow();break;case "接受alert彈窗"://先設置Cell的類型,然后就可以把純數字作為String類型讀進來了 sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();a = seleniumUtil.switchToPromptedAlertAfterWait(Long.parseLong(testData));a.accept();break;case "取消alert彈窗"://先設置Cell的類型,然后就可以把純數字作為String類型讀進來了 sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();a = seleniumUtil.switchToPromptedAlertAfterWait(Long.parseLong(testData));a.dismiss();break; case "執行JS點擊":locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);seleniumUtil.executeJS("arguments[0].click();", seleniumUtil.findElementBy(getLocateWay(locateSplit[0], locateSplit[1])));break; case "刷新頁面":seleniumUtil.refresh();break; case "前進頁面":seleniumUtil.back();break;case "后退頁面":seleniumUtil.forward();break;case "上傳文件":testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();String uploadValues[] = testData.split(",");seleniumUtil.handleUpload(uploadValues[0], new File(uploadValues[1]));break;case "元素被啟用":locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);if(seleniumUtil.isEnabled(getLocateWay(locateSplit[0], locateSplit[1]))){logger.info(getLocateWay(locateSplit[0], locateSplit[1])+"元素被啟用");}else{Assert.fail(getLocateWay(locateSplit[0], locateSplit[1])+":沒有被啟用");}break;case "元素未啟用":locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);if(seleniumUtil.isEnabled(getLocateWay(locateSplit[0], locateSplit[1]))){Assert.fail(getLocateWay(locateSplit[0], locateSplit[1])+"元素被啟用");}else{logger.info(getLocateWay(locateSplit[0], locateSplit[1])+":沒有被啟用");}break;case "驗證首頁菜單欄文本":locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位//locator.split("\\.")[0]分離出頁面名稱,比如HomePage.我的單據,提取出HomePagelocateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();String menus[] = testData.split(",");for (int i1 = 0; i1 < menus.length; i1++) {seleniumUtil.isTextCorrect(seleniumUtil.findElementsBy(getLocateWay(locateSplit[0], locateSplit[1])).get(i1).getText().trim().toLowerCase(), menus[i1].toLowerCase());}break;default:logger.error("你輸入的操作:["+action+"]不被支持,請自行添加");Assert.fail("你輸入的操作:["+action+"]不被支持,請自行添加");}}}}} View Code

    3.5 更改SeleniumUtil.java

    SeleniumUtil.java代碼如下:

    package com.demo.test.utils;import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.File; import java.util.Calendar; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit;import org.apache.log4j.Logger; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.Dimension; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.ITestContext; import org.testng.ITestResult;/*** @Description 包裝所有selenium的操作以及通用方法,簡化用例中代碼量* */ public class SeleniumUtil {/** 使用Log4j,第一步就是獲取日志記錄器,這個記錄器將負責控制日志信息 */public static Logger logger = Logger.getLogger(SeleniumUtil.class.getName());public ITestResult it = null;public WebDriver driver = null;public WebDriver window = null;public String current_handles="";/**** 啟動瀏覽器并打開頁面* */public void launchBrowser(String browserName, ITestContext context,String webUrl,int timeOut) {SelectBrowser select = new SelectBrowser();driver = select.selectExplorerByName(browserName, context);try {maxWindow(browserName);waitForPageLoading(timeOut);get(webUrl);} catch (TimeoutException e) {logger.warn("注意:頁面沒有完全加載出來,刷新重試!!");refresh();JavascriptExecutor js = (JavascriptExecutor)driver;String status= (String)js.executeScript("return document.readyState");logger.info("打印狀態:"+status);}}/*** 最大化瀏覽器操作* */public void maxWindow(String browserName) {logger.info("最大化瀏覽器:" + browserName);driver.manage().window().maximize();}/*** 設定瀏覽器窗口大小: 設置瀏覽器窗口的大小有下面兩個比較常見的用途:<br>* 1、在統一的瀏覽器大小下運行用例,可以比較容易的跟一些基于圖像比對的工具進行結合* ,提升測試的靈活性及普遍適用性。比如可以跟sikuli結合,使用sikuli操作flash;<br>* 2、在不同的瀏覽器大小下訪問測試站點,對測試頁面截圖并保存,然后觀察或使用圖像比對工具對被測頁面的前端樣式進行評測。* 比如可以將瀏覽器設置成移動端大小(320x480),然后訪問移動站點,對其樣式進行評估;<br>* */public void setBrowserSize(int width, int height) {driver.manage().window().setSize(new Dimension(width, height));}/*** 包裝查找元素的方法 element* */public WebElement findElementBy(By by) {return driver.findElement(by);}/*** 包裝查找元素的方法 elements* */public List<WebElement> findElementsBy(By by) {return driver.findElements(by);}/**導航鏈接到url*/public void navigateTargetUrl(String url){driver.navigate().to(url);logger.info("導航到:"+url);}/*** 包裝點擊操作- By* */public void click(By byElement) {try {clickTheClickable(byElement, System.currentTimeMillis(), 2500);} catch (StaleElementReferenceException e) {logger.error("The element you clicked:[" + byElement + "] is no longer exist!");Assert.fail("The element you clicked:[" + byElement + "] is no longer exist!");} catch (Exception e) {logger.error("Failed to click element [" + byElement + "]");Assert.fail("Failed to click element [" + byElement + "]",e);}logger.info("點擊元素 [" + byElement + "]");}public boolean isEnabled(By by){return driver.findElement(by).isEnabled();}/**提交*/public void submit(WebElement w){try{w.submit();}catch(Exception e){logger.error("在元素:"+w+"做的提交操作失敗");Assert.fail("在元素:"+w+"做的提交操作失敗");}logger.info("在元素:"+w+"做了提交操作");}/*** 包裝點擊操作 -webelment* */public void click(WebElement element) {try {element.click();} catch (StaleElementReferenceException e) {logger.error("The element you clicked:[" + element.toString() + "] is no longer exist!");Assert.fail("The element you clicked:[" + element.toString() + "] is no longer exist!");} catch (Exception e) {logger.error("Failed to click element [" + element.toString() + "]");Assert.fail("Failed to click element [" + element.toString() + "]",e);}logger.info("點擊元素 [" + element.toString() + "]");}/** 不能點擊時候重試點擊操作 */public void clickTheClickable(By byElement, long startTime, int timeOut) throws Exception {try {findElementBy(byElement).click();} catch (Exception e) {if (System.currentTimeMillis() - startTime > timeOut) {logger.warn(byElement+ " is unclickable");throw new Exception(e);} else {Thread.sleep(500);logger.warn(byElement + " is unclickable, try again");clickTheClickable(byElement, startTime, timeOut);}}}/*** 獲得頁面的標題* */public String getTitle() {return driver.getTitle();}/*** 獲得元素的文本* */public String getText(By elementLocator) {return driver.findElement(elementLocator).getText().trim();}/*** 獲得元素 屬性的文本* */public String getAttributeText(By elementLocator, String attribute) {return driver.findElement(elementLocator).getAttribute(attribute).trim();}/*** 包裝清除操作* */public void clear(By byElement) {try {findElementBy(byElement).clear();} catch (Exception e) {logger.error("清除元素 [" + byElement + "] 上的內容失敗!");}logger.info("清除元素 [" + byElement + "]上的內容");}/*** 向輸入框輸入內容* */public void type(By byElement, String key) {try {findElementBy(byElement).sendKeys(key);} catch (Exception e) {e.printStackTrace();logger.error("輸入 [" + key + "] 到 元素[" + byElement + "]失敗");Assert.fail("輸入 [" + key + "] 到 元素[" + byElement + "]失敗",e);}logger.info("輸入:[" + key + "] 到 [" + byElement + "]");}/*** 模擬鍵盤操作的,比如Ctrl+A,Ctrl+C等 參數詳解:<br>* 1、WebElement element - 要被操作的元素 <br>* 2、Keys key- 鍵盤上的功能鍵 比如ctrl ,alt等 <br>* 3、String keyword - 鍵盤上的字母* */public void pressKeysOnKeyboard(WebElement element, Keys key, String keyword) {element.sendKeys(Keys.chord(key, keyword));}/*** 在給定的時間內去查找元素,如果沒找到則超時,拋出異常* */public void waitForElementToLoad(int timeOut, final By By) {logger.info("開始查找元素[" + By + "]");try {(new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>() {public Boolean apply(WebDriver driver) {WebElement element = driver.findElement(By);return element.isDisplayed();}});} catch (TimeoutException e) {logger.error("超時!! " + timeOut + " 秒之后還沒找到元素 [" + By + "]");Assert.fail("超時!! " + timeOut + " 秒之后還沒找到元素 [" + By + "]");}logger.info("找到了元素 [" + By + "]");}/*** 在給定的時間內查詢元素,共嘗試三次,如果第三次還是找不到就報錯,這就可能是網頁性能問題了,響應速度不夠* */public void FindElementUtil3TimesTry(int timeOut, final By By ) {int find=0;int notFindTimes = 0;boolean flag = true;while(flag){if(notFindTimes==3){logger.error("嘗試了3次查找都未查找到元素:"+By+"請檢查是不是網絡或者網站性能問題(響應速度不夠)");Assert.fail("嘗試了3次查找都未查找到元素:"+By+"請檢查是不是網絡或者網站性能問題(響應速度不夠)");}logger.info("開始第"+(notFindTimes+1)+"次查找元素[" + By + "]");try {(new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>() {public Boolean apply(WebDriver driver) {WebElement element = driver.findElement(By);return element.isDisplayed();}});find++;} catch (TimeoutException e) {logger.warn("超時!! " + timeOut + " 秒之后還沒找到元素 [" + By + "],這是第"+(notFindTimes+1)+"次查找!");notFindTimes++;if(notFindTimes<3){refresh();}}if(notFindTimes>0&find!=1){flag = true;}else{flag = false;}}logger.info("找到了元素 [" + By + "]");}/*** 判斷文本是不是和需求要求的文本一致* **/public void isTextCorrect(String actual, String expected) {try {Assert.assertEquals(actual, expected);} catch (AssertionError e) {logger.error("期望的文字是 [" + expected + "] 但是找到了 [" + actual + "]");Assert.fail("期望的文字是 [" + expected + "] 但是找到了 [" + actual + "]");}logger.info("找到了期望的文字: [" + expected + "]");}/*** 判斷編輯框是不是可編輯* */public void isInputEdit(WebElement element) {}/*** 等待alert出現* */public Alert switchToPromptedAlertAfterWait(long waitMillisecondsForAlert) throws NoAlertPresentException {final int ONE_ROUND_WAIT = 200;NoAlertPresentException lastException = null;long endTime = System.currentTimeMillis() + waitMillisecondsForAlert;for (long i = 0; i < waitMillisecondsForAlert; i += ONE_ROUND_WAIT) {try {Alert alert = driver.switchTo().alert();return alert;} catch (NoAlertPresentException e) {lastException = e;}try {Thread.sleep(ONE_ROUND_WAIT);} catch (InterruptedException e) {// TODO Auto-generated catch block e.printStackTrace();}if (System.currentTimeMillis() > endTime) {break;}}throw lastException;}/*** 暫停當前用例的執行,暫停的時間為:sleepTime* */public void pause(int sleepTime) {if (sleepTime <= 0) {return;}try {TimeUnit.SECONDS.sleep(sleepTime); logger.info("暫停:"+sleepTime+"秒");} catch (InterruptedException e) {e.printStackTrace();}}/*** 退出* */public void quit() {driver.quit();}/*** 切換frame - 根據String類型(frame名字)* */public void inFrame(String frameId) {driver.switchTo().frame(frameId);}/*** 切換frame - 根據frame在當前頁面中的順序來定位* */public void inFrame(int frameNum) {driver.switchTo().frame(frameNum);}/*** 切換frame - 根據頁面元素定位* */public void switchFrame(By byElement) {try {logger.info("Start switching to frame [" + byElement + "]");driver.switchTo().frame(findElementBy(byElement));} catch (Exception e) {logger.info("Switch to frame [" + byElement + "] failed");Assert.fail("Switch to frame [" + byElement + "] failed");}logger.info("Switch to frame [" + byElement + "] successed");}/*** 選擇下拉選項 -根據value* */public void selectByValue(By by, String value) {Select s = new Select(driver.findElement(by));s.selectByValue(value);}/*** 選擇下拉選項 -根據index角標* */public void selectByIndex(By by, int index) {Select s = new Select(driver.findElement(by));s.selectByIndex(index);}/** 檢查checkbox是不是勾選 */public boolean doesCheckboxSelected(By elementLocator) {if (findElementBy(elementLocator).isSelected() == true) {logger.info("CheckBox: " + getLocatorByElement(findElementBy(elementLocator), ">") + " 被勾選");return true;} elselogger.info("CheckBox: " + getLocatorByElement(findElementBy(elementLocator), ">") + " 沒有被勾選");return false;}/*** 選擇下拉選項 -根據文本內容* */public void selectByText(By by, String text) {Select s = new Select(driver.findElement(by));s.selectByVisibleText(text);logger.info("你選擇了:"+text);}/*** 獲得當前select選擇的值* */public String getCurrentSelectValue(By by){Select s = new Select(driver.findElement(by));WebElement e = s.getFirstSelectedOption();return e.getText().trim();}/*** 獲取下拉列表的所有選項* @param By:By元素對象* @return 返回所有下拉列表中的選項,如option1,option2,……* */public String getSelectOption(By by) {String value = null;Select s = new Select(driver.findElement(by));List<WebElement> options = s.getOptions();for(int i = 0 ; i< options.size() ; i++){value = value + "," + options.get(i).getText(); } return value.replace("null,","");}/*** 執行JavaScript 方法* */public void executeJS(String js) {((JavascriptExecutor) driver).executeScript(js);logger.info("執行JavaScript語句:[" + js + "]");}/*** 獲得輸入框的值 這個方法 是針對某些input輸入框 沒有value屬性,但是又想取得input的 值得方法* */public String getInputValue(String chose,String choseValue) {String value = null;switch(chose.toLowerCase()){case "name":String jsName = "return document.getElementsByName('"+choseValue+"')[0].value;"; //把JS執行的值 返回出去value = (String)((JavascriptExecutor) driver).executeScript(jsName);break;case "id":String jsId = "return document.getElementById('"+choseValue+"').value;"; //把JS執行的值 返回出去value = (String)((JavascriptExecutor) driver).executeScript(jsId);break;default:logger.error("未定義的chose:"+chose);Assert.fail("未定義的chose:"+chose);}return value;}/*** 執行JavaScript 方法和對象* 用法:seleniumUtil.executeJS("arguments[0].click();", seleniumUtil.findElementBy(MyOrdersPage.MOP_TAB_ORDERCLOSE));* */public void executeJS(String js, Object... args) {((JavascriptExecutor) driver).executeScript(js, args);logger.info("執行JavaScript語句:[" + js + "]");}/*** get方法包裝* */public void get(String url) {driver.get(url);logger.info("打開測試頁面:[" + url + "]");}/*** close方法包裝* */public void close() {driver.close();}/*** 刷新方法包裝* */public void refresh() {driver.navigate().refresh();logger.info("頁面刷新成功!");}/*** 后退方法包裝* */public void back() {driver.navigate().back();}/*** 前進方法包裝* */public void forward() {driver.navigate().forward();}/*** 包裝selenium模擬鼠標操作 - 鼠標移動到指定元素* */public void mouseMoveToElement(By by) {Actions builder = new Actions(driver);Actions mouse = builder.moveToElement(driver.findElement(by));mouse.perform();}/*** 包裝selenium模擬鼠標操作 - 鼠標移動到指定元素* */public void mouseMoveToElement(WebElement element) {Actions builder = new Actions(driver);Actions mouse = builder.moveToElement(element);mouse.perform();}/*** 包裝selenium模擬鼠標操作 - 鼠標右擊* */public void mouseRightClick(By element) {Actions builder = new Actions(driver);Actions mouse = builder.contextClick(findElementBy(element));mouse.perform();}/*** 添加cookies,做自動登陸的必要方法* */public void addCookies(int sleepTime) {pause(sleepTime);Set<Cookie> cookies = driver.manage().getCookies();for (Cookie c : cookies) {System.out.println(c.getName() + "->" + c.getValue());if (c.getName().equals("logisticSessionid")) {Cookie cook = new Cookie(c.getName(), c.getValue());driver.manage().addCookie(cook);System.out.println(c.getName() + "->" + c.getValue());System.out.println("添加成功");} else {System.out.println("沒有找到logisticSessionid");}}}/** 獲得CSS value */public String getCSSValue(WebElement e, String key) {return e.getCssValue(key);}/** 使用testng的assetTrue方法 */public void assertTrue(WebElement e, String content) {String str = e.getText();Assert.assertTrue(str.contains(content), "字符串數組中不含有:" + content);}/** 跳出frame */public void outFrame() {driver.switchTo().defaultContent();}// webdriver中可以設置很多的超時時間/** implicitlyWait。識別對象時的超時時間。過了這個時間如果對象還沒找到的話就會拋出NoSuchElement異常 */public void implicitlyWait(int timeOut) {driver.manage().timeouts().implicitlyWait(timeOut, TimeUnit.SECONDS);}/** setScriptTimeout。異步腳本的超時時間。webdriver可以異步執行腳本,這個是設置異步執行腳本腳本返回結果的超時時間 */public void setScriptTimeout(int timeOut) {driver.manage().timeouts().setScriptTimeout(timeOut, TimeUnit.SECONDS);}/*** pageLoadTimeout。頁面加載時的超時時間。因為webdriver會等頁面加載完畢在進行后面的操作,* 所以如果頁面在這個超時時間內沒有加載完成,那么webdriver就會拋出異常*/public void waitForPageLoading(int pageLoadTime) {driver.manage().timeouts().pageLoadTimeout(pageLoadTime, TimeUnit.SECONDS);}/** 根據元素來獲取此元素的定位值 */public String getLocatorByElement(WebElement element, String expectText) {String text = element.toString();String expect = null;try {expect = text.substring(text.indexOf(expectText) + 1, text.length() - 1);} catch (Exception e) {e.printStackTrace();logger.error("failed to find the string [" + expectText + "]");}return expect;}/*** 獲取當前頁面的URL* */public String getPageURL(){return driver.getCurrentUrl();}/*** 這是一堆相同的elements中 選擇 其中方的 一個 然后在這個選定的中 繼續定位* */public WebElement getOneElement(By bys, By by, int index) {return findElementsBy(bys).get(index).findElement(by);}/*** 上傳文件,需要點擊彈出上傳照片的窗口才行* * @param brower* 使用的瀏覽器名稱* @param file* 需要上傳的文件及文件名*/public void handleUpload(String browser, File file) {String filePath = file.getAbsolutePath();String executeFile = "res/script/autoit/Upload.exe";String cmd = "\"" + executeFile + "\"" + " " + "\"" + browser + "\"" + " " + "\"" + filePath + "\"";try {Process p = Runtime.getRuntime().exec(cmd);p.waitFor();} catch (Exception e) {e.printStackTrace();}}/*** @Description 對于windows GUI彈出框,要求輸入用戶名和密碼時,* seleniumm不能直接操作,需要借助http://modifyusername:modifypassword@yoururl 這種方法* * */public void loginOnWinGUI(String username, String password, String url) {driver.get(username + ":" + password + "@" + url);}/** 檢查元素是否顯示 */public boolean isDisplayed(WebElement element) {boolean isDisplay = false;if (element.isDisplayed()) {logger.info("The element: [" + getLocatorByElement(element, ">") + "] is displayed");isDisplay = true;} else if (element.isDisplayed() == false) {logger.warn("The element: [" + getLocatorByElement(element, ">") + "] is not displayed");isDisplay = false;}return isDisplay;}/**檢查元素是不是存在*/public boolean doesElementsExist(By byElement){try{findElementBy(byElement);return true;}catch(NoSuchElementException nee){return false;}}/** 檢查元素是否被勾選 */public boolean isSelected(WebElement element) {boolean flag = false;if (element.isSelected() == true) {logger.info("The element: [" + getLocatorByElement(element, ">") + "] is selected");flag = true;} else if (element.isSelected() == false) {logger.info("The element: [" + getLocatorByElement(element, ">") + "] is not selected");flag = false;}return flag;}/*** 判斷實際文本時候包含期望文本* * @param actual* 實際文本* @param expect* 期望文本*/public void isContains(String actual, String expect) {try {Assert.assertTrue(actual.contains(expect));} catch (AssertionError e) {logger.error("The [" + actual + "] is not contains [" + expect + "]");Assert.fail("The [" + actual + "] is not contains [" + expect + "]");}logger.info("The [" + actual + "] is contains [" + expect + "]");}/*** 判斷實際文本,不包含期望文本* * @param actual* 實際文本* @param expect* 期望文本*/public void isNotContains(String actual, String expect) {try {Assert.assertFalse(actual.contains(expect));} catch (AssertionError e) {logger.error("The [" + actual + "] is contains [" + expect + "]");Assert.fail("The [" + actual + "] is contains [" + expect + "]");}logger.info("The [" + actual + "] is not contains [" + expect + "]");}/** 獲得屏幕的分辨率 - 寬 */public double getScreenWidth() {return java.awt.Toolkit.getDefaultToolkit().getScreenSize().getWidth();}/**進入新窗口*/public void switchNewWindow(By byElement){//獲取當前頁面句柄current_handles = driver.getWindowHandle();//點擊某個鏈接會彈出一個新窗口 click(byElement);//接下來會有新的窗口打開,獲取所有窗口句柄Set<String> all_handles = driver.getWindowHandles();//循環判斷,把當前句柄從所有句柄中移除,剩下的就是你想要的新窗口Iterator<String> it = all_handles.iterator();while(it.hasNext()){if(current_handles == it.next()) continue;//跳入新窗口,并獲得新窗口的driver - newWindowwindow = driver.switchTo().window(it.next());}}/**回到原始窗口*/public void backToOriginalWindow(){window.close();driver.switchTo().window(current_handles);}/**停止頁面加載*/public void stopLoad(){ pause(1);Robot r;try {r = new Robot();r.keyPress(KeyEvent.VK_ESCAPE);logger.info("按下了Esc鍵");r.keyRelease(KeyEvent.VK_ESCAPE);logger.info("松開了Esc鍵");} catch (AWTException e) {e.printStackTrace();}logger.info("正在停止頁面加載...");}/**獲取系統時間*/public int getDate(String getOption){Calendar a=Calendar.getInstance();int result=0;switch(getOption){case "年":result = a.get(Calendar.YEAR);break;case "月":result = a.get(Calendar.MONTH)+1;break;case "日":result = a.get(Calendar.DATE);break;default:Assert.fail("只支持輸入年、月、日。你輸入了:"+getOption);}return result;}/**判斷alert是否出現*/public boolean isAlertPresent(){try{driver.switchTo().alert();logger.info("alert出現");return true;} catch (NoAlertPresentException Ex){logger.warn("alert沒有出現");return false;} }/**CMP干部績效管理系統登錄操作*/public void loginCMP(String username,String password){ FindElementUtil3TimesTry(30, By.id("account"));FindElementUtil3TimesTry(30, By.id("password"));FindElementUtil3TimesTry(30, By.id("bLogin")); type(By.id("account"),username);type(By.id("password"),password);click(By.id("bLogin"));}/*** 在多個相同元素中,定位到指定的元素* @param by* @param index* @return*/public WebElement getOneElement(By by, int index) {List<WebElement> element = driver.findElements(by);return element.get(index);}/*** 獲取指定table某一整列的值*/public String getColumnText(By by){String values = null;List<WebElement> elements = findElementsBy(by);for(WebElement e: elements){String value = e.getText();if(value.length() > 0){values = values + "," + value;} }return values.replace("null,", "");}/*** 獲取指定table某一行的值* @param index:行號,行號從1開始(0代表table的表頭)*/public String getRowText(By by, int index){String values = null;List<WebElement> rows = findElementsBy(by); //tr對象WebElement row = rows.get(index); if(row.findElements(By.tagName("td")).size()>0){List<WebElement> cells = row.findElements(By.tagName("td")); //td對象for(WebElement cell:cells){String value = cell.getText();if(value.length() > 0){values = values + "," + value;}}}return values.replace("null,", "");}/*** 獲取指定table個單元格的值* @param index:行號,行號從1開始(0代表table的表頭)*/public String getCellText(By by, int RowID, int ColID){String value = null;//得到table元素對象WebElement table = driver.findElement(by);//得到table表中所有行對象,并得到所要查詢的行對象。List<WebElement> rows = table.findElements(By.tagName("tr"));WebElement theRow = rows.get(RowID);//調用getCell方法得到對應的列對象,然后得到要查詢的文本。value = getCell(theRow, ColID).getText(); return value.replace("null,", "");}/*** * @param Row: 一行的對象* @param ColID:對應列* @return*/private WebElement getCell(WebElement Row,int ColID){List<WebElement> cells;WebElement target = null;//列里面有"<th>"、"<td>"兩種標簽,所以分開處理。if(Row.findElements(By.tagName("th")).size()>0){cells = Row.findElements(By.tagName("th")); target = cells.get(ColID);}if(Row.findElements(By.tagName("td")).size()>0){cells = Row.findElements(By.tagName("td"));target = cells.get(ColID);}return target;}/*** 在給定的時間內去查找元素,如果沒找到則超時,拋出異常* */public boolean isShown(int timeOut, final By By) {boolean flag = true;logger.info("開始查找元素[" + By + "]");try {(new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>() {public Boolean apply(WebDriver driver) {WebElement element = driver.findElement(By);return element.isDisplayed();}});} catch (TimeoutException e) {flag = false;} return flag;}/**頁面過長時候滑動頁面 window.scrollTo(左邊距,上邊距); */public void scrollPage(int x,int y){String js ="window.scrollTo("+x+","+y+");";((JavascriptExecutor)driver).executeScript(js);}} View Code

    ?

    轉載于:https://www.cnblogs.com/Ming8006/p/5757984.html

    總結

    以上是生活随笔為你收集整理的Selenium Web 自动化 - 项目实战(三)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。