How to take screenshot using Selenium WebDriver?

Whenever we execute a test case using Selenium scripts or any other automation tool, and it fails, it’s important to take the screenshot so that this screenshot can be used later on when we inspect the cause of its failure. It helps us to debug and identify the problem by seeing the screenshot.

To take a screenshot, there is a method called getScreenshotAs() defined in an Interface called TakesScreenshot.

Method to take screenshot:

public void takeScreenShot(WebDriver oBrowser, String sFileName){

	try {
		TakesScreenshot oCamera;

		File oTmpFile, oImageFile;

		oImageFile = new File(sFileName);

		if(new File(sFileName).exists()){
			throw new Exception("Image File already exists.. choose some different name");
		}

		oCamera = (TakesScreenshot) oBrowser;

		oTmpFile = oCamera.getScreenshotAs(OutputType.FILE);

		FileUtils.copyFile(oTmpFile, oImageFile);

	} catch (Exception e) {
		e.printStackTrace();
	}
}

Call this method to take the screenshot. The argument passed is the name of the file with an extension of the file.

For any questions, suggestions or feedback, feel free to call us at amrita@qatechhub.com or support@qatechhub.com. Happy learning 🙂

Saurabh Dhingra

About the Author

Saurabh Dhingra

Follow Saurabh Dhingra: