How to Change Google Chrome User Agent in Selenium with C#
By FoxLearn 12/9/2024 9:59:53 AM 165
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
11/14/2024
Gentella Admin Template
11/14/2024
Material Lite Admin Template
11/14/2024
Carpatin Admin Dashboard Template
11/17/2024