Capture Screenshot In Selenium

Capture Screenshot in Selenium


During our day to day testing we often need to capture screenshots for reporting purposes. Selenium provides an interface named as ITakesScreenshot which takes screenshot of the webDriver.

Syntax: ((ITakesScreenshot)driver).GetScreenshot();

Program: To capture screenshot of www.facebook.com and save the image as "FB.PNG" in "c:\Temp folder".

using System; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Drawing.Imaging; //Used to save image
namespace hello_world
{
  class Program
   {
     static void Main(string[] args)
      {
        //Creates an instance of chrome browser
        IWebDriver chrome = new ChromeDriver();

        //Opens facebook webpage
        chrome.Navigate().GoToUrl("https://www.facebook.com");


        //Takes screenshot
        Screenshot ss = ((ITakesScreenshot)chrome).GetScreenshot();


        //saves in c:\Temp as FB.PNG
        ss.SaveAsFile(@"C:\TEMP\FB.PNG", ImageFormat.Png);
      }
      }
}



Result
FB.PNG Image stored in c:\Temp






























The captured image can also be stored in different format such as JPEG,BMP,GIF and so on.
Example:To store as FB.JPEG all you need to do is change the extension of file to "FB.JPEG" and use ImageFormat.jpeg
 ss.SaveAsFile(@"C:\TEMP\FB.JPEG", ImageFormat.Jpeg));


In our next tutorial let us learn to read data from EXCEL sheet and use it selenium webdriver!


No comments:

Post a Comment