Take Screenshot of Whole Webpage using Selenium WebDriver

Selenium Webdriver has provided one interface TakesScreenshot that one can use in its scripts to capture screen shots.
Interface provides one method getScreenshotAs() that takes an argument of type OutputType.File so that it could return screen shot in file type.

Command to capture screen shot is as follows :-

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

We have taken the screen shot using above command and assigned it to srcFile variable. Now we need to copy the captured screen shot in our machine. For this, there is method copyFile() of FileUtils class that will help us to accomplish this task.

Command to copy the screen shot in your machine is as follows :-

FileUtils.copyFile(scrFile, new File("c:\\gmailHomePage.jpg"));

Below is the small program that would open Gmail login page and would take a screen shot of it.

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

 
public class Sample {
  WebDriver driver;
  String baseUrl;
 
  @BeforeTest
  public void start() {
    driver = new FirefoxDriver();
    baseUrl = "http://www.gmail.com";
    System.out.println("Launch Application");
    driver.get(baseUrl);
  }
 
  @Test
  public void testApp() throws InterruptedException, IOException {
     File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
     FileUtils.copyFile(scrFile, new File("c:\\gmailHomePage.jpg")); 
     Thread.sleep(2000);
  }
 
  @AfterTest
  public void close() {
    //closes browser
    driver.quit();
  }
}

If you really like the information provided above, please don’t forget to leave the comment. You can also like us on Facebook.

Leave a Reply

Your email address will not be published. Required fields are marked *