web自動化腳本運行失敗,很大一部分問題出在元素定位上,博主在這里介紹一個循環定位及失敗截圖的方法。以方便腳本維護,定位問題。
1、以下代碼是WebDriver自帶的方法,封裝一下,使用即可。
1 /** 2 * 截取屏幕截圖并保存到指定路徑 3 * 4 * @param filepath 5 * 保存屏幕截圖完整文件名稱及路徑 6 * @return 無 7 */ 8 public void captureScreenshot(String filepath) { 9 File screenShotFile = ((TakesScreenshot) driver)10 .getScreenshotAs(OutputType.FILE);11 try {12 FileUtils.copyFile(screenShotFile, new File(filepath));13 } catch (Exception e) {14 e.PRintStackTrace();15 }16 } 2、截圖公共方法,生成存放路徑和文件名,打印失敗信息,需要手動創建好目錄文件。
/** * 截圖公共方法,生成存放路徑和文件名,打印失敗信息 * * @param isSucceed * if your Operation success */ public void operationCheck(String methodName, boolean isSucceed) throws Exception { if (!isSucceed) { Date date = new Date(); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HHmmss"); String time = format.format(date); StringBuffer sb = new StringBuffer(); String captureName = sb.append("./Captures/") .append(methodName).append(time).append(".png").toString(); captureScreenshot(captureName); System.out.println("method 【" + methodName + "】 運行失敗,請查看截圖快照:" + captureName); } }
3、在指定的超時時間內,循環定位頁面元素,成功則隨時返回true,超時時間內沒有定位到元素,則執行截圖方法,返回false
1 /** 2 * wait for the specified element appears with timeout setting. 3 * 4 * @param locator 5 * the element locator on the page 6 * @param timeout 7 * 超時時間,單位:秒 8 */ 9 public boolean isElementPresent(By locator, long timeout) throws Exception {10 boolean isSucceed = false;11 long timeBegins = System.currentTimeMillis();12 do {13 try {14 driver.findElement(locator);15 isSucceed = true;16 break;17 } catch (Exception e) {18 e.printStackTrace();19 }20 21 } while (System.currentTimeMillis() - timeBegins <= timeout * 1000);22 23 operationCheck("isElementPresent", isSucceed);24 return isSucceed;25 }4、定位頁面元素公共方法,每次定位元素都調用isElementPresent方法。解決元素未加載完成就點擊的問題。
1 /** 2 * 定位頁面元素,超時時間內反復判斷元素是否出現。若元素定位失敗,則截圖 3 * 4 * @param by 5 * 頁面元素 6 * @param timeout 7 * 超時時間 8 * @return 頁面元素 9 */10 public WebElement getElement(By by, long timeout) {11 try {12 if (isElementPresent(by, timeout)) { 13 return driver.findElement(by);14 }15 } catch (Exception e) {16 System.out.println(e + "");17 }18 return null;19 }5、默認超時時間5秒,腳本使用時直接調用getElement(By by)即可
1 /** 2 * 定位頁面元素,超時時間內反復判斷元素是否出現。若元素定位失敗,則截圖 3 * 4 * @param by 5 * 頁面元素 6 * @return 頁面元素 7 */ 8 public WebElement getElement(By by) { 9 return getElement(by, 5);10 }新聞熱點
疑難解答