selenium 截圖 添加時間戳


 

在自動化程序中運行的代碼報錯信息或者是相關日志有可能並無法直觀的判斷出錯信息。因此截圖是避免不了的。為了避免因為重復運行或者是圖片名稱相同導致截圖被覆蓋。

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

 

 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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM