Running Selenium without a GUI

Running Selenium without a GUI is known as running it in “headless” mode. In this mode, the browser doesn’t display a user interface, which is particularly useful for automated tests that run on servers or other environments where a graphical display is not available.

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace MySeleniumApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize ChromeDriver options
            ChromeOptions options = new ChromeOptions();
            options.AddArgument("--headless");  // Run headless
            
            // Initialize the Chrome Driver with options
            using (IWebDriver driver = new ChromeDriver(options))
            {
                // Navigate to Google
                driver.Navigate().GoToUrl("https://www.google.com");

                // Optionally, capture the page title to verify
                Console.WriteLine("Page title is: " + driver.Title);

                // Close the driver
                driver.Quit();
            }
        }
    }
}

Chrome will run in headless mode, performing all the actions but without displaying the browser GUI. You should see the page title printed in the console if everything works correctly.

The ability to run tests in headless mode can be particularly useful in an automated testing environment or a CI/CD pipeline.

Install Selenium WebDriver for .NET Core

Run the following command to install the Selenium WebDriver NuGet package:

dotnet add package Selenium.WebDriver

You’ll also need to download the WebDriver executable for the browser you intend to use. For example, if you are planning to use Chrome, you’ll need to download ChromeDriver.

You can download it from the official site and place the executable in a directory that is in your system’s PATH, or specify its location in your code.

Write Your Test Code

Now you can write your Selenium test code in the Program.cs file. Here’s a simple example to open Google’s homepage:

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace MySeleniumApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize the Chrome Driver
            using (IWebDriver driver = new ChromeDriver())
            {
                // Navigate to Google
                driver.Navigate().GoToUrl("https://www.google.com");

                // Close the driver
                driver.Close();
            }
        }
    }
}