How to Capture Screenshot using Selenium WebDriver?

The TakesScreenShot interface in the WebDriver library is implemented by all of the different variants of WebDriver, such as Firefox Driver, Internet Explorer Driver, Chrome Driver, and so on.

The TakesScreenShot capability is enabled in all of the browsers by default.

The API syntax for getScreenshotAs() is as follows:

 public <X> X getScreenshotAs(OutputType<X> target)

Here, OutputType is another interface of the WebDriver lib. We can ask WebDriver to give your screenshot in three different formats; they are:

 BASE64

BYTES (raw data),

FILE.

 If you choose the FILE format, it writes the data into a .png file, which will be deleted once the JVM is killed. So, you should always copy that file into a safe location so that it can be used for later reference.

The return type is a specific output that depends on the selected OutputType.

OutputType.BYTES will return a byte array,

OutputType.FILE will return a file object.

Depending on the browser used, the output screenshot will be one of the following in the order of preference:

  1. The entire page
  2. The current window
  3. A visible portion of the current frame
  4. The screenshot of the entire display containing the browser
  • using Firefox Driver, getScreenshotAs() takes the screenshot of the entire page,
  • using Chrome Driver, getScreenshotAs() returns only the visible portion of the current frame.

code example:

    File scrFile = ((TakesScreenShot)driver).getScreenshotAs(OutputType.FILE);
  System.out.println(scrFile.getAbsolutePath());

The getScreenshotAs() method to take the screenshot of the webpage and save it to a file format.

 The getAbsolutePath() method returns the path of the saved image, which you can open and examine.