How to Capture .JPG Screen Shot in .Net Core Framework, a Headless Browser as a Service

C# & .Net Core

Let's see how easy it is to get started with C#, .Net Core , Puppeteer and 0Browser.

In this example we will learn how to take a screen shot of a web page using C#, Puppeteer and 0Browser. But first, let's make sure you have everything ready on your setup!

Prerequisites

1. Install .Net Core

Download and install .Net Core from this web page.

2. 0Browser API Key

Also keep your 0Browser Account API Key handy.
If something doesn't add up here, please check out our Get API Key guide for all details on this.

Setup

Now that we have the prerequisites in order, let's get to the fun part!

1. Create New Project

Run the following command to create a new folder and .net project.
> dotnet new console -n 0browser_puppeteer_demo

2. Open Project

Open the project in your favorite IDE. If you have Visual Studio Code installed you can open the project using below command.
> code .

3. Add Puppeteer

Run the following command to add and restore puppeteer dependency to the project.
> dotnet add package PuppeteerSharp

3. Connect & Capture Screen Shot

No we need to modify Program.cs to include the core logic.
Following code snippet shows how to connect to 0Browser proxy to navigate to the Google page and capture a .JPG screen-shot.

using System;
using System.Threading.Tasks;
using PuppeteerSharp;

namespace _0browser_puppeteer_demo
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var options = new ConnectOptions()
            {
                BrowserWSEndpoint = "wss://proxy.0browser.com?token={YOUR-API-KEY}&timeout=60000",
            };

            using (var browser = await PuppeteerSharp.Puppeteer.ConnectAsync(options))
            {
                using (var page = await browser.NewPageAsync())
                {
                    await page.GoToAsync("https://www.google.com");
                    await page.ScreenshotAsync("capture.jpg");
                    await page.CloseAsync();
                }
            }            
        }
    }
}

Run

Now that all is in place, you can run the C# console application using the following commands.

> dotnet build
# this will build the project

> dotnet run
# this will run the app

Then you will find a new file called capture.jpg in the same directory as your .Net app.
Thats it, Great job!


...
0Browser