How to Change Google Chrome User Agent in Selenium with C#
By FoxLearn 12/9/2024 9:59:53 AM 157
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#
Categories
Popular Posts
Motiv MUI React Admin Dashboard Template
11/19/2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
11/17/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024