Capture Screenshot in Selenium WebDriver using FileHandler Class
Are you wondering why FileUtils is not working to capture screenshot. Is your eclipse not showing any suggestion when you hover on FileUtils. Don’t worry. Its an update in Selenium. In the latest version of Selenium, FileHandler class is implemented to capture screenshot instead of FileUtils.
Here is a sample program to use FileHandler in a Selenium script to capture a screenshot.
Given a detailed explanation inside the program for your understanding.
We have to import package “org.openqa.selenium.io.FileHandler” to work with FileHandler class
Here is a sample program.
package com.amazon.qa.tests; import java.io.File; import java.io.IOException; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.io.FileHandler; import org.testng.annotations.Test; public class FileHandlerClass { @Test public void fileHandlerTest() throws WebDriverException, IOException { //Initialize webdriver System.setProperty("webdriver.chrome.driver","C:\\Selenium Project\\Drivers\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); // To open Softwaretestingmaterial.com site driver.get("https://www.softwaretestingmaterial.com/"); // Following code captures the screenshot and place it in specified location TakesScreenshot ts=(TakesScreenshot)driver; FileHandler.copy(ts.getScreenshotAs(OutputType.FILE), new File("C:\\Selenium Project\\CaptureScreenshot.png")); driver.quit(); } }
Before Selenium 3.6.0, Apache Commons Library comes along with Selenium. But in Selenium new versions from Selenium 3.6.0 onwards, we have to download it separately to use it in our project.
You can download it from https://commons.apache.org/
If you are using Maven Project, here is the dependency of Apache Commons Library
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-io --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency>
If you have any queries, please comment below.