Sunday, February 21, 2016

Taking a Screenshot - Selenium WebDriver

  • Create a Project and package
  • Add Selenium jar
  • In this example, we are taking the screenshot of a webpage and saving that with the timestamp and as a .png file in preferred location(In this example, D:\Hemanth\Screenshots folder)

Example:

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
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;
import org.testng.annotations.Test;
public class TakeScreenshot {

  @Test

  public void myTest() throws Exception {

  WebDriver driver;
        driver = new FirefoxDriver();
        driver.get("http://stlc4u.blogspot.in");
        driver.manage().window().maximize();
       
        File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        Calendar currentDate = Calendar.getInstance();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateN = dateformat.format(currentDate.getTime());
        System.out.println("Date:" + dateformat);
        String filename = "screenshot"+dateN+ ".png";
        File destinationFile = new File("D:\\Hemanth\\Screenshots\\"+ filename);
        FileUtils.copyFile(screenshot, destinationFile);
        driver.close();     
      
    }
}


Screenshot Path and Name:



Output:
 

No comments:

Post a Comment