How to take ScreenShot & save it with different filenames by using Selenium & Java?


You can create a function and pass the desired name to it, something like this:

public static void takeScreenshot(String name) {
        File screenshotFile = ((TakesScreenshot) DriverFactory.getDriver()).getScreenshotAs(OutputType.FILE);
    String fileName = name;
    try {
        fileName += "_" + new Timestamp(System.currentTimeMillis()).toString() + ".png";
        FileUtils.copyFile(screenshotFile, new File(fileName));
    } catch (IOException e) {

For taking the screenshot use below code, In the code I have used a string called DateName which adds current date and time and this will create a new entry of screenshot which will be different from older one.

you can create a method and pass the driver and screenshot name and call that method any where u want it

String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
String screenshotName = NewScreenGrab

//this is the Interface which has different methods 
TakesScreenshot takesScreenshot = (TakesScreenshot) driver;
File screenshotSourceFile = takesScreenshot.getScreenshotAs(OutputType.FILE);

//Below code decides the destination of ur screenshot and type of file
String destination =  System.getProperty("user.dir") + "mention the destination where you want to store the screenshot"+ screenShotName + dateName +".png";

File screenshotDestinationFile = new File(destination);

//Below code copies the screenshot file to required destination
FileUtils.copyFile(screenshotSourceFile, screenshotDestinationFile.getAbsoluteFile());

Not the answer you're looking for? Browse other questions tagged or ask your own question.