Selenium WebDriver: TakesScreenshot method

This is how you can take a screengrab in Selenium WebDriver using 'TakesScreenshot' method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public static void screenGrab(String screengrabFolder, String browser){
 String date = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss").format(new Date());

 System.out.println("trying to take screengrab");
 try{
  File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
  FileUtils.copyFile(scrFile, new File(screengrabFolder+date+"_"+browser+".png"));   
  System.out.println("screengrab taken");
 }catch(Exception e){ 
  //System.out.println("Screengrab error: "+e);
  e.printStackTrace();
 }
}

The method takes screenshot for all browsers: Firefox, Chrome, Internet Explorer and Edge. The file name is dynamic and is saved in .png format. You can save in any format you want. It is suppose to take full page screenshot, but it is a know issue in Chrome, IE and Edge that it takes only visible area screengrab. These are the screengrabs using the above method for different browsers:


Firefox: It takes full page shot.



Chrome: The method captures the image of ONLY the visible part of the browser.



IE: The method captures the image of ONLY the visible part of the browser.



Edge: The method captures the image of ONLY the visible part of the browser.



This how you can use the above method:


1
2
3
 
screenGrab(screengrabFolder, browser);
 

When I want to capture screenshot only when there is an error, I use this method in the 'catch' part of the try-catch method.

No comments:

Post a Comment