import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public static void main(String[] args) throws InterruptedException, IOException { //定義一個前綴文件夾 String prefix="D:/test"; WebDriver dr = new FirefoxDriver(); String url = "http://www.cnblogs.com/"; dr.get(url); Thread.sleep(3000);
//截圖 File screenShotFile =((TakesScreenshot)dr).getScreenshotAs(OutputType.FILE);
//文件命名 File file = new File(prefix+File.separator+System.currentTimeMillis()+".png"); File tempDir = new File(prefix);
//判斷根目錄文件夾是否存在 if (!tempDir .exists() || !tempDir .isDirectory()){ tempDir .mkdir(); } else{ int i=1; while(file.exists()){
//命名重復就后綴加_1 file = new File(prefix+File.separator+System.currentTimeMillis()+"_"+i+".png"); } }
//輸出 FileUtils.copyFile(screenShotFile, file); }