Selenium C# – Open a URL

Pankaj KumarPankaj Kumar
2 min read

Introduction

Selenium is a powerful open-source tool for automating web applications across different browsers. In this blog, we will explore how to open a URL using Selenium in C#.

C# Code to Open a URL Using Selenium

Below is a simple C# test script that demonstrates how to launch Chrome, navigate to a website, and close the browser after a short wait.

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SACSSAuto.QA.SeleniumPractice
{
    [TestClass]
    public class Selenium_04
    {
        /****
        *  Sample Code Definition :- Selenium Test - Browser - Get
        *  Developed  By :- Pankaj Kumar
        *  Date of Creation :- 26-Jan-2025
        *  Project :- SACSSAUTO - C# [Web / Mobile / API]
        */
        [TestMethod]
        public void Selenium_Test()
        {
            Console.WriteLine("Selenium Test - Browser - Get");

            // Open Chrome Browser
            WebDriver driver = new ChromeDriver();

            // Maximize the Browser
            driver.Manage().Window.Maximize();

            // Open the URL (same as Get in Selenium Java)
            driver.Url = "https://practice.solveautomation.in/";

            // Wait for 5 Seconds
            Thread.Sleep(5000);

            // Quit the Driver
            driver.Quit();
        }
    }
}

Explanation of the Code

  1. Setting up the Selenium WebDriver:

  2. Writing the Test Method:

    • The method Selenium_Test() is marked with [TestMethod] to indicate it’s a test case.

    • We create a new instance of ChromeDriver to launch the browser.

    • The browser window is maximized for a better view.

    • The test navigates to a sample practice site (https://practice.solveautomation.in/).

    • The Thread.Sleep(5000); command pauses execution for 5 seconds to observe the browser action.

    • Finally, driver.Quit(); closes the browser.

Running the Test

To execute the test:

  1. Open Visual Studio and create a new MSTest Project.

  2. Add Selenium WebDriver and ChromeDriver NuGet packages.

  3. Copy and paste the above code into your test file.

  4. Run the test using Test Explorer in Visual Studio.

0
Subscribe to my newsletter

Read articles from Pankaj Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pankaj Kumar
Pankaj Kumar