In this article, we will see how we can take screenshots in selenium. This is done by using the takeScreenshot offered by the selenium library.
Why ScreenShots?
- This is done to reduce manual effort.
- Captured screenshots during the test are handy.
- Screenshots help monitor tests every time by time it gets executed.
- Screenshots can also help when a test case fails and identify the wrongs.
- When the GUI is not visible during headless test execution, screenshots are beneficial.
- We can store it in our customized destination.
ScreenShot In Action:
- To take screenshots, TakeScreenshot is used, which enables the selenium webdriver to capture and store.
- It also comes with getScreenShotAs(), which captures screenshot and stores it in the desired location.
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
- Webdriver object is converted into TakeScreenshot.
- OutputType also accompanies them. File to create an image file.
FileUtils.copyFile(screenshot , new File("C:\\main\\image.png));
- Using the file utils, we then pass the source and destination of the image to be stored.
package week4.day2;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class Screenshot {
public static void main(String[] args) throws Throwable {
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.programsbuzz.com/user/login");
driver.manage().window().maximize();
driver.findElement(By.id("edit-name")).sendKeys("Naruto");
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenshot, new File("C:\\TestLeaf\\UsernameSC.png"));
} catch (IOException e) {
System.out.println(e.getMessage());
}
driver.quit();
}
}

- Here we have taken a screenshot of the page after inputting the username.
- Then stored, it in our specified location using fileutils.