How to Change Google Chrome User Agent in Selenium with C#
By FoxLearn 12/9/2024 9:59:53 AM 203
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 use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
Admin BSB Free Bootstrap Admin Dashboard
11/14/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024
Spica Admin Dashboard Template
11/18/2024