Selenium C# Tutorial: Capturing screenshots with Selenium WebDriver

Updated: Jan 18


Selenium WebDriver provides the capability to capture screenshots during test execution. This ability is vital when you need to investigate different failures that occurred during the execution or, in some cases, to track the various stages of the run.


The option to take a screenshot with selenium is extracted from the "ITakesScreenshot" interface that allows us to take a web page screenshot. We can also capture screenshots during verification of element state, values displayed, or state after an action is complete.


Capturing screenshots is vital when you need to debug a test that fails during execution; one of the best practices that I use in my teams is that we Capture baseline screenshots before the test is executed for some significant scenarios and another screenshot at the end of the test. This approach will increase the team's ability to visually debug any failure and see the actual result instead of just relaying the errors in the test framework.


So, how to do it...?

In the following example, the ITakesScreenshot interface is used for capturing

the screenshot using the Screenshot class:


Note:

To work with different file formats, please install the NuGet package https://www.nuget.org/packages/System.Drawing.Common/

using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.IO;
using System.Text;
using System.Drawing;
using System.Drawing.Printing;

namespace TestProject1._0
{
    [TestClass]
    public class UnitTest1
    {
        static IWebDriver driver;        

        [ClassInitialize]
        public static void ClassInitialize(TestContext context)
        {      
            driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.agilequalitymadeeasy.com/");            
            Console.WriteLine("SetUp Finished Successfully");
        }
     
        [TestMethod]        
        public void TakeScreenshotDefaultImageFormat()
        {
            try
            {
                Screenshot TakeScreenshot = ((ITakesScreenshot)driver).GetScreenshot();
                TakeScreenshot.SaveAsFile("c:\\Screenshot Example\\HomePage_1");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }
        [TestMethod]
        public void TakeScreenshotPNGformat()
        {
            //Using the SaveAsFile() method. We can specify the desired format using System.Drawing.Imaging.ImageFormat.
            try
            {
                Screenshot TakeScreenshot = ((ITakesScreenshot)driver).GetScreenshot();
                TakeScreenshot.SaveAsFile("c:\\Screenshot Example\\HomePage_2." + System.Drawing.Imaging.ImageFormat.Png);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }
        
        [TestMethod]
        public void TakeScreenshotJPEGformat()
        {
            try
            {
                Screenshot TakeScreenshot = ((ITakesScreenshot)driver).GetScreenshot();
                TakeScreenshot.SaveAsFile("c:\\Screenshot Example\\HomePage_3." + System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }

        [ClassCleanup]
        public static void ClassCleanup()
        {
           //close the web driver
           driver.Quit();
        }
    }
}

Result:



And here is another example using the "screenshot image format":

[TestMethod]
        public void TakeScreenshotJPEGformat()
        {
            try
            {
                Screenshot TakeScreenshot = ((ITakesScreenshot)driver).GetScreenshot();
TakeScreenshot.SaveAsFile("c:\\Screenshot Example\\ImageFormat." + ScreenshotImageFormat.Tiff);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }

Result:

If you try to save your screenshot in your local drive, you may get an error when the folder specified in the path is not created/not available. Let's see how can we avoid this scenario by a simple IF clause:

[TestMethod]
        public void TakeScreenshotJPEGformat()
        {
            DirectoryInfo Validation = new DirectoryInfo("c:\\Screenshot Example"); //System IO object

            if (Validation.Exists == true)
            {
                Screenshot TakeScreenshot = ((ITakesScreenshot)driver).GetScreenshot();
                TakeScreenshot.SaveAsFile("c:\\Screenshot Example\\ImageFormat." + ScreenshotImageFormat.Tiff);

            }
            else
            {
                Validation.Create();
                Screenshot TakeScreenshot = ((ITakesScreenshot)driver).GetScreenshot();
                TakeScreenshot.SaveAsFile("c:\\Screenshot Example\\ImageFormat." + ScreenshotImageFormat.Tiff);
            }
        }


Taking screenshot for a specific element

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

 [TestMethod]
        public void TakeScreenshotForSpecificElement()
        {
            IWebElement ElementToCapture;
            
          
            //Select a specific element 
            ElementToCapture = driver.FindElement(By.CssSelector("#img_comp-kgwowrt01 > img:nth-child(1)"));

            //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 a Screenshot and save it on a TMP file
            ((ITakesScreenshot)driver).GetScreenshot().SaveAsFile("c:\\Screenshot Example\\ImageFormat.png", ScreenshotImageFormat.Png);

            //import The File that we save earlier
            Bitmap ImportFile = new Bitmap("c:\\Screenshot Example\\ImageFormat.png");

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

            //Save extracted file 
            CloneFile.Save("c:\\Screenshot Example\\SpecificWebElement.png");

            //Dispose and Remove TMP file
            ImportFile.Dispose();            
            File.Delete("c:\\Screenshot Example\\ImageFormat.png");
        }

Result:



978 views0 comments