Saturday 20 August 2016

Selenium: WebDriver: Taking screen shots

Whenever you are running number of test cases using selenium web driver, it is always good to take screen shots of failed test cases. In this post, I am going to explain how to take screen shot.

Selenium provides TakesScreenshot interface to capture the screenshot and store it in the specified location.

Following is the prototype of TakesScreenshot interface.

public interface TakesScreenshot {
  <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException;
}

Depends on the browser implementation, the output screen shot can be one of the following.
a.   Entire page
b.   Current window
c.    Visible portion of the current frame
d.   The screenshot of the entire display containing the browser

getScreenshotAs(OutputType<X> target)
As you observe the above function, it takes OutputType as an argument. OutputType specifies the output type for a screenshot. OutputType provides following constants to specify the output type.

Constant
Description
OutputType.BASE64
Obtain the screenshot as base64 data. It is defined like
OutputType<String> BASE64 = new OutputType<String>() {
   .....
   .....
}
OutputType.BYTES
Obtain the screenshot as raw bytes. It is defined like
OutputType<byte[]> BYTES = new OutputType<byte[]>() {
   ....
   ....
}
OutputType.FILE
Obtain the screenshot into a temporary file that will be deleted once the JVM exits. Always take a backup of the file, before JVM exits. It takes screen shot as .png file.

For example,
Following lines take screen shot of google.com.

driver.get("http://google.com");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("google.png"));


Following is the complete working application.
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;

public class App {
   public static void main(String[] args) throws IOException {
      WebDriver driver = new FirefoxDriver();
      
      driver.get("http://google.com");
      File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(scrFile, new File("google.png"));
      
      driver.close();
   }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment