Best way to take screenshot of a web page into Selenium?


We can take screenshots of a web page with Selenium. It is a three way process. Taking a screenshot is one of the most essential steps towards defect and failure analysis.

First, we have to convert the driver object to the TakeScreenshot interface.

Syntax

TakesScreenshot s = (TakesScreenshot)driver;

Next, we have to take the help of the getScreenshotAs method to have an image file and finally copy the file to a location with FileUtils.copyFile method.

Syntax

File src=s.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("file path"));

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class ScreenshotCapture{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // screenshot capturing
      File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(src, new File("careerpage.png"));
      driver.quit();
   }
}

Updated on: 28-Nov-2020

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements