How to take screenshot of a webpage in C# with Selenium in 4 steps

How to take screenshot of a webpage in C#

Table of Contents

Spread the love

So, How do you take a screenshot of a webpage in C#?

I have explained how we can capture screenshots of the website from its URL using Selenium (C# screenshot library).

And at the end, there is a C# script to take screenshots of the webpage automatically.

Projects like this let you have fun while also learning the programming language. So, whether you’re a Beginner, Intermediate, or an advanced C# developer.

I hope you’ll definitely learn something.

So, in simple words.

How to take screenshot of a webpage in C#?

To take a screenshot of a webpage in C# we use Selenium Web Driver, and some C# code. A separate function is declared outside the main function and is coded to capture the screenshot. It is then called in the main function. This is a small C# application that allows you to capture any web page as an image and save it to your PC without any third party. The C# script to take a screenshot of a web page automatically is given within the Blog Post.

Here’s what we’ll be covering Step-by-Step.

  1. Download and Install Microsoft Visual Studio (Community Edition)
  2. Downloading the Chrome Driver
  3. How to take a screenshot of a webpage in C#
  4. Free Code to take screenshots, with C# screenshot library

Let's get started.

Download and Install Microsoft Visual Studio (Community Edition)

Download and Install Microsoft Visual Studio.

You can Click Here to download it directly.

Now find where you Downloaded the executable Visual Studio Setup file and open it.

The installation Process is Pretty self-explanatory.

When you open the file, the Installer will open. Click Continue.

Then Visual Studio will Download and Install on its own.

After the above Process is Completed, a new window will pop up, as shown below.

Click on .NET desktop development.

On the right side, you can see what Tools will be installed.

Leave everything as default and click on Install.

It will take some time to install, depending on your internet connection.

It will install everything like The .NET Framework, the Just in Time Compiler, and some other needed libraries and software.

After this finishes you can click on Launch to start Visual Studio.

Select Your Theme, as per your requirements. Leave the Developmental Settings to General.

You’ll be taken to the below screen.

If you’ve followed along so far. Congratulations. You’ve successfully set up Visual Studio on your PC and now are ready to Code and learn how to take screenshot of a webpage in c#.

Download Chrome Driver

Before you learn how to take screenshot of a webpage in c#, you have to download the chrome driver executable for this to Work.

To download the Chrome Driver:

https://www.chromedriver.chromium.org/downloads

From here you have to select a version of the driver that matches the version of the chrome browser you’re currently using.

For example, If my chrome browser version is 100, then I’ll download the chrome driver version 100

Below is my current version of Chrome.

And I’ll download this version of the Driver

After downloading the Chrome Driver, save it in a location where it is easy to access.

How to take screenshot of a webpage in C#

Now as we have Downloaded and installed both Visual studio and Chrome Browser Successfully, we can continue with our Project on how to take screenshot of a webpage in c#.

Open Visual Studio, and set up a C# file

Click on “Create a new Project”

Select Console Application .net core

Why console? To make things simple.

This is also helpful if you want to turn this into an API, service, or a small script, in the future.

Name the Project. (In my case it is WebScreenShot.)

Click Next

Save it into the relevant directory.

Select .NET 5, (you can also select 6 if you want)

Hit Create, and here we are in the C# File and environment where all the magic happens.

How to take a screenshot of a webpage in c#

So let’s just delete the Hello world.

Move out of the main function.

Here we will define our own function that will take the screenshot of the webpage.

We will declare a public function named CaptureWebpage which takes a string as an argument.

That string is the URL of the webpage from which you want to capture the screenshot.

We will Declare the Capture Screenshot function like this

The Function Will Look Like this now at the start

public static void CaptureWebPage (string url)

{

        /* the body of the function goes here */

}

Now I will discuss the lines of code within this function step-by-step. Then I will also show the Complete C# script to take a screenshot of the webpage automatically.

Including Selenium Library

Before we go ahead and capture a Screenshot with C#, we will have to install some libraries, which will help us take a website screenshot.

Remember: Libraries extend the functionality of a language.

On Your Visual Studio Project Window. Look on the Right side and right under the Solution Explorer, you will see your Project name.

Under that, you will see an option named Dependencies.

Right-click on Dependencies.

And Select Nuget Packages.

Simply go to Browse.

Search for Selenium Web Driver

Click on the one that shows up on the top.

Select it, and a new window will appear.

Find the Install option for the selenium web driver, and install it.

Just wait a moment, and Visual Studio will Install and Configure the Selenium WebDriver for Your C# Web Screenshot Capture Project.

What is a selenium Webdriver or C# Screenshot Library?

In simple terms, it allows you to automate web browsing. Like for basic tasks, instead of you wasting your time, You can use selenium web driver, to save your time through web automation. There are a vast variety of things you can do with selenium. This Website screenshot is just a small part of what selenium can actually do.

For example in this Project on How to take screenshot of a webpage in C#, we will use Selenium to:

. Open Google Chrome Programmatically with C# code.
. Do some Automations (In this case Take a Webpage Screenshot)
. And Close the Browser.

This is a pretty small but Powerful Project to get your feet into the world of Web Automation.

I’m also planning to do Advanced Projects regarding Web Automation.

So, subscribe to our email list if you don’t want to miss them.

Anyways, Let’s Continue.

Explanation of each line of code on how to take a screenshot of a webpage in c#

Now, let’s go back to our main function and start coding.

/**/
Import chrome Options
/**/

Declaring Variable options

We will start by declaring the web browser options or chrome options we’re going to use with Selenium Web Driver.

We will do it as follows:

/**/
Var options = new ChromeOptions();
/**/

What is a Headless Argument?

Then we will Add an Argument known as Headless.

This simply means that your code opens the browser in stealth mode.

Meaning that The Chrome Browser is opened within the code without any interface and you cannot see it on the screen.

Adding Headless Argument

We add the headless argument as follows

/**/
options.AddArgument(“--headless”)
/**/

What is a User-Agent Argument?

Now we will add the user agent argument.

It’s simply an argument that will tell the browser, That the Code is behaving like a real human being. So to make the browser avoid Detecting us as a bot.

Adding user Agent Argument

We add the User-Agent Argument in C# as follows:

 options.AddArgument("user-agent-Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");

Creating a Driver Object and passing Options as Parameter

Now let’s use Webdriver and create a new ChromeDriver and pass it the

Options variable as the parameter.

We will also give the path to the chrome driver we downloaded earlier here below in this function parameters.

/**/
IWebDriver driver = new ChromeDriver(“E:\\TechVideos\\Python”, options);
/**/

Passing the URL

Now we will use this newly created driver object, to Navigate the Url and visit it by:

/**/
driver.Navigate().GoToUrl(url);
/**/

How to take screenshot of a webpage in c#

Now we have the URL opened within our code, and now we actually want To do the real thing this code is supposed to do “Take the Screenshot”.

For that, we will use the ITakesScreenshot interface that is pre-coded within the selenium Library.

/**/
ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
/**/

Now we have to create a new Screenshot object to actually capture or Get the screenshot.

/**/
Screenshot screenshot = screenshotDriver.GetScreenshot();
/**/

Until now our screenshot was saved within the screenshot object within the c code

Saving Screenshot from Code to Local Storage

But now we want to take it out of the code and save it on our Local Storage

On our Computer.

For this, we will use the SaveAsFile method of the screenshot object

Like shown below

/**/
screenshot.SaveAsFile("Test.png");
/**/

You can give any name you want your screenshot to have. I have given Mine as Test.png

Calling the Capture Webpage Function in the Main Function

Now as we have completed our CaptureWebPage function. We can head back over to the Main function and call this function to test it out, whether it actually works, and whether are we successfully able to take a Website Screenshot with C#

In your Main function.

Call the function by its name and pass in the URL from which you want to take the screenshot.

/**/
CaptureWebPage(“https://learnwithhasan.com”);
/**/

How to take screenshot of a webpage in C# (Source Code)

/* START */
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;


namespace WebScreenShot{
    internal class HelloWorld
    {
        public static void Main(string[] args)
        {
            CaptureWebPage("https://learnwithhasan.com");
        }
        
        public static void CaptureWebPage(string url){
            var options = new ChromeOptions();
            options.AddArgument("--headless")
            options.AddArgument("user-agent-Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
            IWebDriver driver = new ChromeDriver(“E:\\TechVideos\\Python”, options);
            
            driver.Navigate().GoToUrl(url);
            
            ITakesScreenshot screenshotDriver = 
            driver as ITakesScreenshot;
            
            Screenshot screenshot = 
            screenshotDriver.GetScreenshot();
            
            screenshot.SaveAsFile("Test.png");
        }
}
}
/* END */

How to take a screenshot of a webpage in C# (Output)

Now to find your Output Image, Follow the following Path.

Your_ProjectFolder > Bin > Debug > net5.0 > Test.png

Conclusion on how to take screenshot of a webpage in c#

As you now have a successful Code Snippet in C# that does some

Web automation i.e (takes webpage screenshots).

It’s up to you. You can turn it into an API, Sell it, or use it on your own PC.

It’s like a small gift from me to you.

Moreover, if you want to do the same thing in Python, you can check this out.

If you found this tutorial helpful, Don’t forget to share it with your friends. And Check out our Other Tutorials.

You Can find the Project Source Code on Github

If you have any problems regarding this Project of Taking Website Screenshot with C# you can post your queries in the comments below.

We'll be happy to help.

Take Care, and Keep Coding!!!


Spread the love