Take screenshots and name file using timestamp in Selenium

| By Webner

When we test a website and face bugs we need screenshot of the output to suggest to the developer to fix the issue. Automated testing is usually evidenced by Screenshots and logs. But how to save screenshots with timestamp in the file name using Selenium?

In this example we will follow these steps:

1. Access the url “https://time.is/India”
2. Take the screenshot of the page which is showing indian time
3. Con the california time
4. Take the screenshot
5. Exit


package testing;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Screenshot
public static WebDriver driver;
public void openbrowser(String url) throws IOException
//Open the browser
System.setProperty("webdriver.chrome.driver", "C:/chromedriver.exe");
driver = new ChromeDriver();

// Maximize the window size

// Open the url

// Call the screenshot method to take a screenshot

//Click on the button for open the next page

//Again call the method to capture the screenshot of next page

//Close the browser
public static void main(String[] args) throws IOException
Screenshot call = new Screenshot();

// Take screenshot method
Private void captureScreenshot(String fileName,String extension)throws IOException

// Take the screenshot and store as file format
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

// Open the current date and time
String timestamp = new SimpleDateFormat("yyyy_MM_dd__hh_mm_ss").format(new Date());

//Copy the screenshot on the desire location with different name using current date and time
FileUtils.copyFile(scrFile, new File("C:/shots/" + fileName+" "+timestamp+extension));


1. File scrFile = ((TakesScreenshot)driver)
–This statement converts the webdriver object into the screenshot.

2. getScreenshotAs(OutputType.FILE);
–This method captures the screenshot.

3. String timestamp = new SimpleDateFormat(“yyyy_MM_dd__hh_mm_ss”).format(new Date());
–It returns the current date and time.

4. FileUtils.copyFile(scrFile, new File(“C:/shots/” + fileName+” “+timestamp+extension));
–It saves the screenshot to the desired location and we use the timestamp variable to save the screenshot with a different name every time


After running the script it saves the screenshots like this:

Leave a Reply

Your email address will not be published. Required fields are marked *