Take screenshot of a web page using Selenium Web Driver (Java)

  • Given any web page, we would like to take its screenshot using Selenium Web Driver.
  • We can use this screenshot for reporting purpose or for raising a bug in case of a test case failure.
  • We can capture the screenshot of any web page using three simple steps:
    • Step 1 : Cast WebDriver object to TakeScreenshot object using
      ((TakesScreenshot) driver).
    • Step 2: Use
      getScreenshotAs(OutputType.FILE)

      method to create an image file.

    • Step 3: Now copy the image file to desired location on your Machine using :
      FileUtils.copyFile(src, new File("D:\\Performance testing\\facebookPic.png"));
      • Screenshot (Image) file will be saved on your machine at specified location. e.g : (
        D:\\Performance testing\\facebookPic.png

        )

    • Now, Go to a specific location on your machine (
      D:\\Performance testing\\facebookPic.png

      ), we will be able to find the screenshot image file there.

package org.learn;

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.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class takeScreenshot {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		
		System.setProperty("webdriver.chrome.driver", "C:\\\\work\\\\chromedriver.exe");
		WebDriver driver = new ChromeDriver();
		driver.get("https://www.facebook.com/");
		driver.findElement(By.id("email")).sendKeys("Username123");
		File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
		FileUtils.copyFile(src, new File("D:\\Performance testing\\facebbok.png"));

	}

}

Scroll to Top