Invoke Chrome browser in headless mode using Selenium 4 and C#

Versions used while doing this blog post, (These are the prerequisites to automate chrome browser. Browser and driver versions should match)
selenium python version – 4.7.0
chrome browser version – 108
chrome driver version – 108 (Download link : https://chromedriver.chromium.org/downloads) [Selenium manager auto downloads the driver version]

Opening chrome in headless mode fastens the execution. This mode is really helpful for distributed executions.

Headless chrome browser can be opened using selenium by following below steps:

1. Instantiate an object with ChromeOptions() class and set argument to start the browser in headless mode. We have set an argument to ‘headless’

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("headless");

2. Instantiate (creation of object) driver object with ChromeDriver() (This step opens the chrome browser)

IWebDriver driver = new ChromeDriver(chromeOptions);

3. Now, next steps of maximizing the browser, setting implicit timeout for driver object and launch of expected website can be carried out

driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(15);
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl("https://www.google.com");

4. Quit/close the driver object after automating the necessary flows within the website.

driver.Quit();

Sample code for reference

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

namespace Selenium4CsharpExamples
{
    public class OpenChromeHeadlessUsingSelenium4
    {
        static void Main(string[] args)
        {
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.AddArguments("headless");
            IWebDriver driver = new ChromeDriver(chromeOptions);
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(15);
            driver.Manage().Window.Maximize();
            driver.Navigate().GoToUrl("https://www.google.com");
            driver.Quit();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *