How to take screenshot in selenium webdriver

Taking screenshots is very useful and needful if yo are a tester. While logging bug or generating report developers or manager will ask for screenshots if anything fails. While running automation with selenium web-driver, it provides facility to take screenshots. It's very easy. If you are just starting with selenium webdriver first go through this for first hello world script. "How to start automation with selenium webdriver"

How to take screenshot in selenium webdriver
How to take screenshot in selenium webdriver

Taking screenshot with selenium 

To take screenshot using selenium just go through following JAVA code -


import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public class takeScreenShotInSelenium {

public static void main(String args[]) throws Exception {
//Set path of Chrome driver
System.setProperty("", "C:\\chromedriver.exe");
//opens chrome browser
WebDriver driver = new ChromeDriver();
//maximize chrome
//hit the link
//waits for site  to open
//take screenshot and store in file
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//save the file at given location
FileUtils.copyFile(scrFile, new File("./ScreenShots/Facebook_screenshot.png"));
Explanation - 
we are casting driver object to TakesScreenshot. Now with this driver you can access method getScreenshotAs. This method will retun a screenshot file. You can save this file at provided location using java File i/o.

Optimize code
Here, in each script we need take screenshots multiple times, may be on failures or at critical scenarios. So it would be better if you create one JAVA method in common utilities and call that method whenever it requires. you can also add screenshot name in method arguments.

public takeScreenshotInSelenium(WebDriver driver, String screenshotName)

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//save the file at given location
FileUtils.copyFile(scrFile, new File("./ScreenShots/+"screenshotName"+"));
Now you can call this method in each scripts whenever it required. Keep in mind Whenever you write this code, make sure you add correct imports.

1 comment: