Step 1: Create a New Project
Open a terminal window in Visual Studio Code.
Navigate to the folder where you want to create your new project.
Type dotnet new console -n MySeleniumProject to create a new console application.
Step 2: Add Selenium WebDriver NuGet Package
Navigate into your project folder in the terminal (cd MySeleniumProject).
Type dotnet add package Selenium.WebDriver --version 3.141.0 to add the Selenium WebDriver package to your project.
Step 3: Add WebDriver Manager (Optional)
For ease of management, you can also add WebDriver Manager which will automatically manage the browser driver for you.
bash
Copy code
dotnet add package WebDriverManager --version 2.11.0
Step 4: Add Selenium Code
Open your Program.cs file and add the necessary using statements and Selenium code. Below is a sample code to open Google and search for "Hello World":
csharp
Copy code
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
namespace MySeleniumProject
{
class Program
{
static void Main(string[] args)
{
// Setup ChromeDriver using WebDriverManager
new DriverManager().SetUpDriver(new ChromeConfig());
// Initialize Chrome Driver
IWebDriver driver = new ChromeDriver();
// Navigate to Google
driver.Navigate().GoToUrl("https://www.google.com");
// Find search box using its name attribute
IWebElement searchBox = driver.FindElement(By.Name("q"));
// Type "Hello World" in the search box
searchBox.SendKeys("Hello World");
// Submit the search
searchBox.Submit();
// Wait for a bit (this is not the best practice, but serves for demonstration purposes)
System.Threading.Thread.Sleep(5000);
// Close the Chrome browser
driver.Quit();
}
}
}
Step 5: Run Your Code
Go back to the terminal and navigate to your project directory. Run the command dotnet run to execute your program. This should open up a new Chrome window and perform a Google search for "Hello World".
And there you have it! You've set up a Selenium WebDriver project in C# using Visual Studio Code.