How to Change Google Chrome User Agent in Selenium with C#
By Tan Lee Published on Dec 09, 2024 273
To change the user agent in Google Chrome when using Selenium in C#, you'll need to use the ChromeOptions class to set the custom user agent string, and then pass those options when launching the Chrome browser.
Steps to Change the User Agent in Chrome with Selenium in C#
You can install the Selenium WebDriver for C# via NuGet.
Install-Package Selenium.WebDriver Install-Package Selenium.WebDriver.ChromeDriver
Next, Use the ChromeOptions
class to add a custom user agent.
// Create an instance of ChromeOptions ChromeOptions options = new ChromeOptions(); // Set the custom user agent string string userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"; options.AddArgument($"user-agent={userAgent}"); // Initialize the Chrome WebDriver with the specified options IWebDriver driver = new ChromeDriver(options); // Navigate to a website to verify the user agent driver.Navigate().GoToUrl("https://www.foxlearn.com"); // Wait for user input to close the browser Console.WriteLine("Press any key to close the browser..."); Console.ReadKey(); // Close the browser driver.Quit();
Creates a new instance of ChromeOptions and sets the custom user agent string using the AddArgument method.
Categories
Popular Posts
Portal HTML Bootstrap
Nov 13, 2024
Freedash bootstrap lite
Nov 13, 2024
Motiv MUI React Admin Dashboard Template
Nov 19, 2024
K-WD Tailwind CSS Admin Dashboard Template
Nov 17, 2024