Selenium WebDriver : How to take screenshot and save it to particular location with timestamp.

/*

Selenium WebDriver : How to take screenshot and save it to particular location with timestamp.

 *
 */

This is a simple utility program which helps to capture a screenshot in Web automation using Selenium WebDriver.

User can enhance this program to save output file with their own requirement of timestamp and the file format in which they want to save.



import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

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 class Screenshot_Demo_Selenium {

 /**
  * @param args<!-- ?xml version="1.0" encoding="iso-8859-1"? -->
  */
 public static void main(String[] args) throws IOException {

// Create browser instance, to know how to set and invoke different browser click here:
  WebDriver driver = new FirefoxDriver();  
  
  driver.get("https://twitter.com");   // provide the URL to browse
  driver.manage().window().maximize();  // maximize the browser
  
  //Java class which formats date and time in a given manner
  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
  Date date = new Date();
  
  String fileName = (dateFormat.format(date)).toString();
  System.out.println(fileName);
  
  
  //Using below function TakesScreenshot which is type-casted to driver whose output type is File.
  File sourceFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); 
  
  //Using copyFile function which take 2 parameters , sourceFile and destination file( where you can provide the path with the file extension )
// System.getProperty("user.dir") - provide the current directory path.
  FileUtils.copyFile(sourceFile, new File(System.getProperty("user.dir")+"\\screenshots\\"+fileName+".jpg"));
  
  //quit() is a selenium function which close and quits the driver.
  driver.quit();
  
 }

}

No comments:

Post a Comment

πŸ””Announcement : Visit the new website/blog πŸ””

πŸ””πŸ””πŸ”” Announcement :  Visit the new website/blog πŸ””πŸ””πŸ”” Dear readers, Thank you for reading my blog. If you could have used the little info...