How to run headless chromedriver in C#
By FoxLearn 11/16/2024 4:49:57 AM 5
Headless mode is an execution mode for Firefox and Chromium-based browsers, enabling users to run automated scripts without displaying the browser window.
This mode is commonly used for tasks like web scraping or testing. In Selenium, there are convenience methods available in most language bindings to easily enable headless mode by adjusting the browser's options.
How to run headless Chrome with Selenium in C#?
To run Chrome in headless mode, you need to configure the ChromeOptions
to run without the GUI.
Before you begin, ensure you have the necessary NuGet packages for Selenium WebDriver and ChromeDriver.
Install-Package Selenium.WebDriver
How to run Chrome in headless mode?
Chrome introduced an updated headless mode starting with version 96, which allows users to access full browser functionality, including running extensions.
Initially, between versions 96 and 108, the mode was activated with `--headless=chrome`, but from version 109 onward, it changed to `--headless=new`. This new mode is expected to provide a better experience when using headless with Selenium.
// Set Chrome options for headless mode ChromeOptions options = new ChromeOptions(); options.AddArgument("--headless=new"); // Enable headless mode options.AddArgument("--disable-gpu"); // Disable GPU hardware acceleration (sometimes necessary in headless mode) options.AddArgument("--no-sandbox"); // Disable sandboxing (required in some environments) // Create an instance of ChromeDriver with the options IWebDriver driver = new ChromeDriver(options); // Navigate to a webpage driver.Navigate().GoToUrl("https://foxlearn.com");
Once you’ve interacted with the browser, use driver.Quit()
to clean up and close the browser instance.
The ChromeOptions class allows you to configure various options for ChromeDriver. In the code above, options.AddArgument("--headless")
tells Chrome to run without the graphical user interface (headless).
To play demo, you need to download chromedriver.exe, then copy into your project.
See how to download chromedriver.exe
This is the basic setup for running a headless Chrome instance using Selenium WebDriver in C#.