Selenium with C# for Automated Browser Testing
Last Updated : 24 Apr, 2025
Selenium is used to automate the desktop browser testing. It comes up with many components and from them, the major one is the web driver. Web driver is used for writing the code in different programming languages which will target the web elements and then apply the operation on it. We can use C#, Java, Python, and many other languages which can be used to work with it.
Why is C# useful for Automation Testing?
Using C# we easily do automation Testing. It is an open source and due to this different frameworks have support for this language.
- There is a specialized package Manager known as NuGet Package Manager which comes up with so many different kinds of Packages.
- Using these packages the testing work becomes easier. In C# we can also merge the unit testing with automation testing frameworks and this gives us so much power to check the result without running each script separately.
Selenium with C#
Selenium and C# become a solid combination because C# is one of the chosen languages to work with Selenium due to so many functions to manipulate and test the Websites. In C# we have NUnit Testing which is again a widely used testing framework and Selenium can be easily integrated with it. Due to this, we can run the unit tests for both the backend and frontend simultaneously and that also in parallel.
Get the elements using their ID or by their class name or their tag Name
C# //Mostly all element in DOM can be accessed using the TagName IWebElement element = driver.FindElement(By.TagName("input")); //Here we are sending the text to the Field which means //that we are writing into the Form Elements element.SendKeys("Text to be entered");
1. For Dropdown
C# // Find the dropdown by its ID IWebElement dropdown = driver.FindElement(By.Id("dropdownId")); // Create SelectElement object to select the value from Dropdown SelectElement selectElement = new SelectElement(dropdown); // Select an option by visible text selectElement.SelectByText("Option to select");
2. For Buttons
C# //Again Finding the button IWebElement button = driver.findElement(By.cssSelector("button[type='submit']")); //Applying the Click function on it. button.click();
We will create a Console Application in which we will create a selenium script and we will interact with the website.
Step 1: Download and install C# IDE (Visual Studio)
- We can download Visual Studio 2022 from the official website.
- If you are a student or learner then you can go with the community version. And if you want to use it for Production or work then you can choose Professional Version as well.
Step 2: Create a New Project in Visual Studio
Choose the Create new project from the Menu.
Creating ProjectStep 3: Select Console Application
1. Now from the list choose the Console Application with C# as the Programming Language.
Creating Console Application2. Our project has been created successfully and now we will install some packages to run the Selenium.
Step 4: Installing NuGet Packages
For creating a selenium application and using selenium methods we have to install 3 packages.
1. Selenium.WebDriver
Selenium.Webdriver2. Selenium.Support
Selenium.Support3. Selenium.Webdriver.ChromeDriver
This will be used to say to Selenium to choose which browser in our case we are going to use Chrome and thus we are installing this Package. If you want to try any other browser then you have to install those packages accordingly.
Chrome Driver PackageStep 5: Installing Chrome Driver
For executing the scripts we will require a Chrome driver which we load as soon as we run the application and all the operations will be executed in that only. We can download the Chrome driver from Here.
Remember you have to choose the version of the driver according to the Current Version of Chrome. If the version doesn't match then an error will be thrown rather than execution.
Chrome DriverSo, now we are good to go with writing the script to automate the browser with Selenium. But before that let's create one HTML form with which we can interact and fill that form using selenium.
Code for HTML Form
HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" /> <title>Form</title> </head> <body> <div class="container mt-5 p-5"> <h1>Form Submission with Selenium</h1> <form class="row g-7" id="myForm" onsubmit="submitForm(event)"> <div class="col-8"> <br /> <div class="mb-3 row"> <label for="FirstName" class="col-sm-2 col-form-label" >FirstName</label > <div class="col-sm-10"> <input type="text" class="form-control" id="FirstName" /> </div> </div> <div class="mb-3 row"> <label for="DOB" class="col-sm-2 col-form-label">DOB</label> <div class="col-sm-10"> <input type="date" class="form-control" id="DOB" /> </div> </div> <div class="mb-3 row"> <label for="Email" class="col-sm-2 col-form-label">Email</label> <div class="col-sm-10"> <input type="email" class="form-control" id="Email" /> </div> </div> <div class="mb-3 row"> <label for="inputNumber" class="col-sm-2 col-form-label" >Number</label > <div class="col-sm-10"> <input type="number" class="form-control" id="inputNumber" /> </div> </div> <div class="mb-3 row"> <label class="col-sm-2 col-form-label" for="Gender">Gender</label> <div class="form-check col-sm-2"> <input class="form-check-input" type="radio" name="Gender" id="Male" value="Male" /> <label class="form-check-label" for="Male">Male</label> </div> <div class="form-check col-sm-2"> <input class="form-check-input" type="radio" name="Gender" id="Female" value="Female" /> <label class="form-check-label" for="Female">Female</label> </div> </div> <button class="btn btn-info col-sm-2" type="submit">Submit</button> </div> </form> </div> <script> function submitForm(event) { // Prevent the form from actually submitting event.preventDefault(); // Extract form data const firstName = document.getElementById("FirstName").value; const dob = document.getElementById("DOB").value; const email = document.getElementById("Email").value; const number = document.getElementById("inputNumber").value; const gender = document.querySelector( 'input[name="Gender"]:checked' ).value; if (!/^\d{10}$/.test(number)) { alert("Error"); return; } // Create a message with the form data const message = `First Name: ${firstName}\nDOB: ${dob}\nEmail: ${email}\nNumber: ${number}\nGender: ${gender}`; // Display an alert with the form data alert(message); document.getElementById("FirstName").value = ""; document.getElementById("DOB").value = ""; document.getElementById("Email").value = ""; document.getElementById("inputNumber").value = ""; document.querySelector('input[name="Gender"]:checked').checked = false; } </script> </body> </html>
Now interacting with this form will help us understand the working and the flow of the selenium application. So we will first get the elements and then on that, we will perform the operations. So, that we can get an idea of both the process.
Selenium Test Script using C#
C# using OpenQA.Selenium; using OpenQA.Selenium.Chrome; namespace Csharp_Application { internal class Program { static void Main(string[] args) { //Creating instance of Chrome Driver IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("http://127.0.0.1:5500/index.html"); try { //Finding the element based on the Id //Then we are Sending the values to those fields driver.FindElement(By.Id("FirstName")).SendKeys("ram"); driver.FindElement(By.Id("DOB")).SendKeys("19-01-2001"); driver.FindElement(By.Id("Email")).SendKeys("[email protected]"); driver.FindElement(By.Id("inputNumber")).SendKeys("1234566890"); driver.FindElement(By.Id("Male")).Click(); //Finding the button and clicking on that button driver.FindElement(By.CssSelector("button[type='submit']")).Click(); //As per the frontend Alert box should get opens //We are tracking that but shifting our control from screen to alert IAlert alert = driver.SwitchTo().Alert(); string alertText = alert.Text; // Check if the alert is open if (!string.IsNullOrEmpty(alertText)) { Console.WriteLine("Alert is open, and the content is: \n" + alertText); // You can accept the alert if needed: alert.Accept(); } else { Console.WriteLine("No alert found"); } } catch (Exception e) { //This will execute when any error like if the url didn't load //Or the browser didn't get open. Console.WriteLine(e.Message); } Console.ReadLine(); driver.Quit(); } } }
In the above code, the FindElement method is used to get the element. We can store these elements in the variable if we want to use them later. In this case, we have directly sent the keys which will be used to write into the field. Later on, we will find the button and then we will click on that.
Output of Selenium Test Script in Visual Studio
OutputConclusion
So, this was basic of the Selenium with C# in which we have just found the element and then applied some operation. We can also move ahead with this, here we have used ID to get the element. But we can use classname or we can also use Xpath. These are the advanced features of selenium in C# which are generally done after this basic one.
Similar Reads
Automated Browser Testing with Edge and Selenium in Python
Cross-browser testing is mandatory in the software industry. We all know that there are many browsers like Firefox, Chrome, Edge, Opera etc., are available. Rather than writing separate code to each and every browser, it is always a decent approach to go towards automated testing. Let us see how to
5 min read
How to Automate TestNG in Selenium?
TestNG is an open-source test automation framework for Java, designed to make the process of testing more efficient and effective. Standing for "Next Generation," TestNG offers advanced features like annotations, data-driven testing, and parallel execution. When combined with Selenium, it provides a
4 min read
Selenium testing without browser.
Selenium Testing without Browser is a method of running automated tests without launching the browser's graphical user interface (GUI). This is achieved using headless browsers, which allow tests to run faster and consume fewer resources. It is ideal for regression testing, continuous integration, a
9 min read
Automation Using Selenium in C# With Example
Selenium is an open-source Web UI automation testing suite. It was developed by Jason Huggins in 2004 as an internal tool at Thought Works. It supports automation across different browsers, platforms, and programming languages which includes Java, Python, C#, etc. It can be easily be deployed on Win
3 min read
Parallel Testing with Selenium
In parallel testing, multiple tests can be run simultaneously in different execution modes, reducing execution time. This approach is particularly useful when running tests across multiple browsers or operating systems because it simplifies cross-browser testing. TestNG is often used with Selenium t
9 min read
How to Automate Click Using Selenium WebDriver?
Selenium is one of the most popular and powerful tools for automating web applications. Selenium is widely used for automating user interactions like filling out forms, clicking on a button, navigating to a web page, and many more. One of the most common tasks while working with Selenium is clicking
6 min read
Run Selenium Tests with Gauge
Gauge is an open-source framework for test automation that is especially useful for Behavior Driven Development (BDD). It is characterized by its simplicity, scalability, and compatibility with other languages, such as Java, C#, and JavaScript. Gauge and Selenium work together to provide reliable, u
5 min read
How to Automate Amazon Like E-Commerce Website with Selenium?
In this article by using Selenium webdriver how to automatically add addresses via a sample Java Program. Quickview of Selenium: Selenium is used for cross-browser automated testing and as it supports a lot of browsers, they are very helpful. For using Selenium in the project we need separate kinds
5 min read
Pros and Cons of Selenium as an Automation Testing tool
Selenium is a free, open-source test execution automation platform for web applications. It implements itself using a browser-specific driver that accepts and transmits commands to the browser. You can develop test scripts in a variety of computer languages, including Ruby, Java, NodeJS, PHP, Perl,
8 min read
Best Practices for Selenium Test Automation
Selenium Test Automation is a cornerstone of modern web application testing. To ensure that your Selenium scripts are both effective and reliable, it's crucial to follow best practices that enhance test quality and maintainability. Implementing the right strategies can save time, reduce troubleshoot
6 min read