Wednesday, May 20, 2020

Screenshot in Selenium

How to capture Screenshot in Selenium Web-driver (C#)

OVERVIEW

Selenium Web-Driver provides the capability to capture screenshots during a test execution. This ability is really important when you need to investigate different failures that occurred during the execution or in some cases to track the different stages of the run.

The capability to take a screenshot with selenium is extracted from the "ITakesScreenshot" interface that allowing us to take a screenshot of the current page displayed in the driver instance.

Taking screenshot of the entire screen (All Elements)

In the following test, we will log into a web-page and take screenshot of the entire page in .JPEG format. We can create screenshot class in common driver and can use in entire project. 

#region screenshots
        // Create a class of screenshot in common driver
        public class SaveScreenShotClass
        {
            public static string SaveScreenshot(IWebDriver driver, string ScreenShotFileName) // Definition
            {
               // Determines where do you going to save the screenshot

                var folderLocation = YourfolderLocation.ScreenshotPath;

                if (!System.IO.Directory.Exists(folderLocation))
                {
                    System.IO.Directory.CreateDirectory(folderLocation);
                }
                // This method will take the screenshot

                var screenShot = ((ITakesScreenshot)driver).GetScreenshot();

                var fileName = new StringBuilder(folderLocation);

                fileName.Append(ScreenShotFileName); // Determine the picture name

                //fileName.Append(DateTime.Now.ToString("_dd-MM-yyyy_mss"));  // Determine the                              picture name with date formate

                fileName.Append(DateTime.Now.ToString("dd-mm-yyyy_mss"));

                fileName.Append(".jpeg");  // Determine the format of the picture

                screenShot.SaveAsFile(fileName.ToString(), ScreenshotImageFormat.Jpeg); //

                return fileName.ToString();
            }
        }

        #endregion

     // Now we can use screenshot method in all project with the help of below code

    SaveScreenShotClass.SaveScreenshot(driver, "PictureName");

No comments:

Post a Comment

Featured Posts