Selenium WebDriver: Robot method

This is how you can take a screengrab in Selenium WebDriver using 'Robot' 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,IE and Edge. The file name is dynamic and is saved in .png format. You can save in any format you want.  It take the screengrab of the entire SCREEN. These are the screengrabs using the above method for different browsers (note the Bookmark bar in the top and Taskbar in the bottom):

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