Getting Started with Selenium in CSharp

by Weijie JIN on

Selenium is a suite of tools to automate web app testing across many platforms.

You may download and use Selenium from

In this post, I would like to introduce the basic usage of Selenium in .Net development.

Create Selenium instance

In Selenium 2.0, there is a concept named WebDriver which is used to interacting with browsers. There are three build-in drivers in Selenium 2.0b3, FirefoxDriver, InternetExplorerDriver, ChromeDriver.

After adding Selenium reference to your project, you can use the Selenium WebDriver to control the browsers to do the automatic things. First, you need to create an instance of one of the drivers:

RemoteWebDriver driver;
public SeleniumDemo()
    driver = new InternetExplorerDriver();

Navigate web pages

When you got your WebDriver instance, you can send commands to WebDriver to operate browsers, for example, let the web browser visit Google:

driver.Url = "";

Find elements in a web page

After landing some page, you probably want to check when some specific elements are on the page. You have several ways to do so thanks to the nice APIs from Selenium. For example, you want to make sure a textbox with id “txtMyData” existing on the page. You can write:

IWebElement txtMyData = driver.FindElementById("txtMyData");

Then you want to set the text of the textbox:

txtMyData.SendKeys( "blar blar blar..." );

After that, you want to submit the form by clicking the submit button:

IWebElement btnSubmit = driver.FindElementById("btnSubmit");

The form should be submitted.

You can use other ways to find elements like by className, xpath, etc.

Wait elements loaded in Selenium

When you do the browser automation, one thing you need to be aware is that you cannot operate elements until they loaded in browser. So in Selenium, there is a way to wait for the element appearing in the page.

For example, in the previous sample, we want to make sure the submit button is loaded before submitting:

first, we need to create an WebDriverWait instance:

RemoteWebDriver driver;
WebDriverWait wait;

public SeleniumDemo()
    driver = new InternetExplorerDriver();
    //the wait will check the element intervally until the expire time.
    wait = new WebDriverWait( driver, new TimeSpan( 0, 0, 3 ) );

Then we change the submitting code:

IWebElement btnSubmit = wait.Until( d => d.FindElement( By.Id( "btnSubmit" ) ) );

Another way to wait when executing:

Thread.Sleep(5000);//wait for 5 seconds


This is just a brief introduction of Selenium. I think you may able to write some automation tests with these basic concepts. It’s a lot of fun playing with Selenium, just try it.Smile

Previous post:

Next post: