Capturing a screenshot of a page

Whenever your test case fails, it is very important to capture screenshot to check the reason of failure. It helps us to debug and identify the problem by seeing the screen shot.

In selenium webdriver, we can capture a screen shot using following command.

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

Capturing a screenshot of a page in Selenium
Example code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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.firefox.FirefoxDriver;

public class DemoScreenShot {

 public static void main(String[] args) throws InterruptedException, IOException {

  System.setProperty("webdriver.gecko.driver", "./ProjectSelenium/driver/geckodriver.exe");
  WebDriver driver = new FirefoxDriver();
  driver.get("https://www.facebook.com");

  try {
   // the below statement will throw an exception as the element is not found,
   // Catch block will get executed and takes the screenshot.
   driver.findElement(By.id("testing")).sendKeys("test");

  } catch (Exception e) {
   System.out.println("I'm in exception");
   File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
   File targetFile = new File("../MyProject/screenshot/" + "ScreenPrint.jpg");
   FileUtils.copyFile(screenshot, targetFile);
  }
 }
}


<-- Previous || Next -->

No comments:

Post a Comment