Friday 12 July 2013

Taking Screenshot using Selenium/WebDriver

Hello Guys,

        How is learning about Selenium going on? In today's post, I would like to discuss about Taking a Screenshot while running Selenium scripts. It is really required for you to take a screenshot at least of your failed test cases in the Test suite. It can save a lot of time, while reviewing the test result.

So let start.... Taking a screenshot in Selenium can be done in couple of ways. 
1) Using Selenium API.
2) If you are using Java binding for script language then Using Java Robot.

We will see both the implementation below. Lets start with Selenium API.

1) Using Selenium API

 
@Test
public void TakingScreenShotUsingSeleniumAPI(){
 try {
 WebDriver driver= new InternetExplorerDriver();
 driver.get("http://google.co.in");
 String fileName=getClass().getSimpleName();
 File screenshot = ((TakesScreenshot)driver)
                  .getScreenshotAs(OutputType.FILE);
 FileUtils.copyFile(screenshot, new File(fileName));
 driver.quit();
  } catch (Exception e) {
 e.printStackTrace();
    }
 }

2) Using Robot class of Java

 
@Test
public void TakingScreenShotUsingRobot(){
 try {
   WebDriver driver= new InternetExplorerDriver();
   driver.get("http://yahoo.co.in");
   String fileName=getClass().getSimpleName();
   Toolkit toolkit = Toolkit.getDefaultToolkit();
   Rectangle screenSize = new Rectangle(0,0,toolkit.getScreenSize()
                    .width,toolkit.getScreenSize().height);
   Robot robot = new Robot();
   BufferedImage bfIimage = robot.createScreenCapture(screenSize);
   ImageIO.write(bfIimage, "png", new File(fileName));
   driver.quit();
  } catch (Exception e) {
      e.printStackTrace();
     }
 }

}


Now you can use any of the above method to take screenshot, Robot screenshot may not work if the PC is locked, So you need to decide which will be good for you to use.

So what do you think about this post? If you are aware of any other way to take a screenshot using Selenium/Java, then please let us all know.

Thanks!!

1 comment:

  1. Nice Article, Please do post this kind of posts more, thanks.
    I wish you might like to have a look at my article http://javaseleniumworld.com/robot-class/

    ReplyDelete

Angular JS Protractor Installation process - Tutorial Part 1

                     Protractor, formally known as E2E testing framework, is an open source functional automation framework designed spe...