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); }