How to Change Google Chrome User Agent in Selenium with C#
By FoxLearn 12/9/2024 9:59:53 AM 60
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.
- How to fix 'Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on'
- How to use BlockingCollection in C#
- Calculating the Distance Between Two Coordinates in C#
- Could Not Find an Implementation of the Query Pattern
- Fixing Invalid Parameter Type in Attribute Constructor
- Objects added to a BindingSource’s list must all be of the same type
- How to use dictionary with tuples in C#
- How to convert a dictionary to a list in C#
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
12/19/2024