selenium 截圖 添加時間戳

 

在自動化程序中運行的代碼報錯信息或者是相關日誌有可能並沒有法直觀的判斷出錯信息。所以截圖是避免不了的。爲了不由於重複運行或者是圖片名稱相同致使截圖被覆蓋。java

建議在截圖時使用時間戳,保證截圖圖片名稱的惟一性。web

 

 1 import java.io.File;
 2 import java.io.IOException;
 3 import java.text.DateFormat;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Calendar;
 6 import org.apache.commons.io.FileUtils;
 7 import org.openqa.selenium.OutputType;
 8 import org.openqa.selenium.TakesScreenshot;
 9 import org.openqa.selenium.WebDriver;
10 import org.openqa.selenium.chrome.ChromeDriver;
11 import org.openqa.selenium.chrome.ChromeOptions;
12 
13 public class GetImg {
14     public static void main(String[] args) {
15         System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe");
16         ChromeOptions Options = new ChromeOptions();
17         Options.addArguments("user-data-dir=C:\\Users\\happy\\AppData\\Local\\Google\\Chrome\\User Data");
18         WebDriver driver = new ChromeDriver(Options);
19         driver.get("https://www.baidu.com/");
20         // 生成以時間戳爲名的截圖,避免圖片重複致使的覆蓋
21         DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
22         Calendar calendar = Calendar.getInstance();
23         String imageName = df.format(calendar.getTime());
24         // 進行截圖 並把截圖保存在指定位置。
25         File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
26         try {
27             FileUtils.copyFile(srcFile, new File("d:\\" + imageName + ".png"));
28         } catch (IOException e) {
29 
30             e.printStackTrace();
31         }
32         driver.close();
33         driver.quit();
34 
35     }
36 }
相關文章
相關標籤/搜索