1. 程式人生 > >selenium 驗證某個測試類某些關鍵步驟時,自動截圖功能

selenium 驗證某個測試類某些關鍵步驟時,自動截圖功能

需要引入的基礎jar包

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
package com.property;

	import java.io.File;
	import java.io.IOException;
	import java.text.SimpleDateFormat;
	import java.util.Date;
	import org.apache.commons.io.FileUtils;
	import org.openqa.selenium.By;
	import org.openqa.selenium.OutputType;
	import org.openqa.selenium.TakesScreenshot;
	import org.openqa.selenium.WebDriver;
	import org.openqa.selenium.firefox.FirefoxDriver;
	import  org.testng.annotations.Test;
	 
	public class ScreenShot {
		@Test
		public void screenshot() throws IOException {
			
			WebDriver driver = new FirefoxDriver();
			// 開啟CSDN登入頁面
			driver.get("http://sso.cserver.com.cn/sso.web/login?service=http%3A%2F%2Fmy.cserver.com.cn%2Fmysystem%2FsaasMysystem.do%3Flayout%3Dsaas");
			
			//try {
				//輸入使用者名稱和密碼,此處專門將密碼輸入錯誤,造出異常現象
				driver.findElement(By.xpath(".//*[@id='username']")).sendKeys("
[email protected]
"); driver.findElement(By.xpath(".//*[@id='password']")).sendKeys("aaa"); driver.findElement(By.xpath(".//*[@name='button1']")).click(); driver.manage().window().maximize(); // 由於密碼輸入錯誤,所以無法進入登陸後頁面,也就無法進行點選“設定”的操作,因此如我們所願,進入catch分支 //driver.findElement(By.linkText("設定")).click(); //} catch (Exception e) { // 列印異常原因,控制檯也會列印 //System.out.println("======exception reason=======" + e); //圖片名稱加時間戳 String dateString = getDateFormat(); // getScreenshotAs()對當前視窗進行截圖 File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); // 需要指定圖片的儲存路徑及檔名 FileUtils.copyFile(srcFile, new File(".\\ScreenShots\\" + dateString + ".png")); //e.printStackTrace(); //} } public static String getDateFormat(){ Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String dateString = sdf.format(date); return dateString; } }

參考二:引自:https://www.cnblogs.com/tobecrazy/p/3599568.html