How to Take a Screenshot in Selenium with C# .NET

How to Take a Screenshot in Selenium with C# .NET

This blog is going to explain how to take a screenshot of a webpage using selenium through C # .NET

You can achieve that in just 2 steps. First take a screenshot using the GetScreenshot() method. Then save it in location.

//Take the screenshot
Screenshot image = ((ITakesScreenshot)driver).GetScreenshot();

//Save the screenshot
image.SaveAsFile(AppDomain.CurrentDomain.BaseDirectory+"//ScreenShot.png", ScreenshotImageFormat.Png);

The following is a full C# console application code. In the code I have found the current version of the chrome browser and downloaded the same webdriver (Check this blog for more information) .Then I take a screenshot of the webpage and save it to the local storage.

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
using WebDriverManager.Helpers;

namespace SampleConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
             // Download the same version of chromedriver
            var chromeDriverPath = new DriverManager().SetUpDriver(new ChromeConfig(), VersionResolveStrategy.MatchingBrowser);

            // Get a path of chromedriver
            string chromeDirectoryPath = System.IO.Path.GetDirectoryName(chromeDriverPath);

            // Create instance by passing the path of the chromedriver directory
            IWebDriver driver = new ChromeDriver(chromeDirectoryPath);

            driver.Navigate().GoToUrl("https://www.google.com/");

            //Take the screenshot
            Screenshot image = ((ITakesScreenshot)driver).GetScreenshot();
            //Save the screenshot
            image.SaveAsFile(AppDomain.CurrentDomain.BaseDirectory + "//Screenshot.png", ScreenshotImageFormat.Png);
        }
    }
}

The following screenshot of the above code.

How to Take a Screenshot in Selenium

I hope this helps you. Keep coding.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

Exploring EventCallback in Blazor: Building Interactive Components

A Step-by-Step Guide to Implementing Identity in ASP.NET Core MVC