Sunday, August 23, 2015

Lesson #17 - Selenium WebDriver – Capturing Screenshots (C#)


Overview

In this article I want to demonstrate a great feature that selenium can offer you, this feature is the ability to capture screenshots in real time during the automated execution.

This ability is really important when you need to investigate different failures that occurred during the execution or in some cases just uses it to track the different stages of the run.

Note!
The ability to take Screenshots is great, but it cannot replace a good log system, the ability to combine both debug tools has been always the suggested way.

Preparations

Remember that each screenshot is a physical file that we need to save, in C# we need to add a specific class that allow us to perform few basic operation in our File System (Reading and Writing), to do so , please add this code:

using System.IO;

Capturing the screen (All Elements)

The first option is to use this ability to capture the entire screen, without specifying a specific element.

Code:

public class UnitTest1
{
//IWebElement WebElement;
static int ScreenCounter = 0; //Will be update per  screenshot that we took

[TestMethod]
public void Screenshots()
{
IWebDriver FirefoxInstance = new FirefoxDriver();
FirefoxInstance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(60));
FirefoxInstance.Navigate().GoToUrl("http://www.dtvisiontech.com");

TakesScreenshotWithDate(FirefoxInstance, @"C:\FileLocation\","File_Name_", System.Drawing.Imaging.ImageFormat.Jpeg);

/*
The Method Arguments:
FirefoxInstance = IWebDriver object that we defined at the start of the code
@"C:\Path\"     = The path that we are going to use to save the screenshots
"Test_Date_"    = The File name that we going to use
System.Drawing.Imaging.ImageFormat.Jpeg = The File Format that we are going to use
*/

private void TakesScreenshotWithDate(IWebDriver BrowserInstance ,string Path,string FileName,System.Drawing.Imaging.ImageFormat Format)
{
ScreenCounter++; //Update the number of screenshot that we took during the execution

StringBuilder TimeAndDate = new StringBuilder(DateTime.Now.ToString());
TimeAndDate.Replace("/","_");
TimeAndDate.Replace(":", "_");

/*

Remember that we cannot save a file with '/' Or ':', but we still need a unique identifier,
Therefore, we need to replace this characters with an acceptable chars.

Before : 12/06/2015 14:54:55
After  : 12_06_2015 14_54_55

* /

DirectoryInfo Validation = new DirectoryInfo(Path); //System IO object

if (Validation.Exists == true) //Capture screen if the path is available
{
((ITakesScreenshot)BrowserInstance).GetScreenshot().SaveAsFile(Path + ScreenCounter.ToString() + "." + FileName + TimeAndDate.ToString() + "." + Format, Format);
}
else //Create the folder and then Capture the screen
{
Validation.Create();
((ITakesScreenshot)BrowserInstance).GetScreenshot().SaveAsFile(Path + ScreenCounter.ToString() + "." + FileName + TimeAndDate.ToString() + "." + Format, Format);
}
}}

Capturing the screen (Specific Elements)

This code will demonstrate how to take a screenshot for a specific element while ignoring the rest of the browser.

Code:


 [TestMethod]
        public void PrinSpecificElement()
        {
            IWebElement ElementToCapture;
            IWebDriver FirefoxInstance = new FirefoxDriver();
            FirefoxInstance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(60));
            FirefoxInstance.Navigate().GoToUrl("http://www.dtvisiontech.com");
            FirefoxInstance.Manage().Window.Maximize();
           
            //Select a specific element from my Blog (The Main Title in this case)
            ElementToCapture = FirefoxInstance.FindElement(By.ClassName("titlewrapper"));


            //Get the element Size
            int The_Element_Width = ElementToCapture.Size.Width;
            int The_Element_Height = ElementToCapture.Size.Height;

            //Get the Element location Via X/Y coordinates
            int The_Element_Location_X = ElementToCapture.Location.X;
            int The_Element_Location_Y = ElementToCapture.Location.Y;

            //Creating the Rectangle that we going to use to extract the element
            Rectangle Test = new Rectangle(The_Element_Location_X, The_Element_Location_Y, The_Element_Width, The_Element_Height);

            //Take Screenshot and save it on TMP file
            ((ITakesScreenshot)FirefoxInstance).GetScreenshot().SaveAsFile(@"c:\TMP.jpeg", ImageFormat.Jpeg);

            //import The File that we save earlier
            Bitmap ImportFile = new Bitmap(@"c:\TMP.jpeg");

            //Clone and extract the requested Element(Based on our Rectangle)
            Bitmap CloneFile = (Bitmap)ImportFile.Clone(Test, ImportFile.PixelFormat);

            //Save The Extract Element
            CloneFile.Save(@"c:\SpecificElementAfter.jpeg");
           
            //Dispose the TMP file that we doesn’t need anymore
            ImportFile.Dispose();
           
            //Delete the TMP file
            File.Delete(@"c:\TMP.jpeg");
        } 


No comments:

Post a Comment

My Presentations