In order to identify the failures of test scripts, It is very important to
capture screenshot when we execute them.
In this post, I will
explain how we can capture screenshots with time stamp using Selenium WebDriver.
Please find the below sample code for the same.
Sample code:
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
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.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class TakeScreenShot {
public WebDriver driver;
@Test
public void setup() throws IOException{
System.setProperty("webdriver.chrome.driver", "E:/Selenium Jars/chromedriver.exe");
driver= new ChromeDriver();
//System.setProperty("webdriver.gecko.driver", "C:/Users/sudharsana/Downloads/geckodriver.exe");
//driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://way2selenium.com");
//screenshot
takesScreenshot(driver, "Home Page");
}
//Reusable Method for capturing screenshot
public void takesScreenshot(WebDriver driver , String ScreenshotName) throws IOException{
//Creating Object for Date
Date date = new Date();
//Creating object for time stamp
Timestamp timestamp= new Timestamp(date.getTime());
//converting date format to String
String time=timestamp.toString();
//replacing all spaces with '-'
time = time.replace(' ', '-');
//replacing all colons with '-'
time = time.replace(':', '-');
//Capturing screenshot as File output type
File screen=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//copying screenshot to local machine directory
FileUtils.copyFile(screen, new File(System.getProperty("user.dir")+"\\Screenshots\\"+"_"+ScreenshotName+"_"+time+"_"+"_"+".jpg"));
}
}
Hi Sudharsan,
ReplyDeleteGreat info on capturing screenshots with timestamps using Selenium WebDriver. I love reading about more ways to efficiently utilize java programming in business.
Hope to connect soon,
Dennis
Nice post
ReplyDeleteAstrologer in Chennai