Selenium 2.0 WebDriver with Visual Studio, C#, & IE – Getting Started

Selenium Published on:
selenium ie

In this post I'll show you how to configure Selenium 2.0 WebDriver to work with Visual Studio and Internet Explorer. (For some reason, I initially had a hard time getting this configured correctly.)

After much googling and trying different solutions from various places, I finally got Selenium work. Hopefully this post will help you avoid some of the issues I ran in to.

UPDATE: When your done with this post be sure to check out my interview with Jim Evans, the guy behind the Selenium.Net bindings and the IEDriver to ask him how to make your tests more reliable against IE. Check it out Selenium and IE – Getting Them to Work Together.

Download the  Selenium C# Client Drivers

  • The first step is to download the C# dlls from Selenium's web site.
  • You'll also want to download the Internet Explorer Driver Server:


  • Once you've downloaded the required Selenium files, extract the zips to a local drive on your computer

FYI – the Selenium Web Drivers work against IE 6,7,8 and 9 both 32-bit and 64-bit versions.

How to Configure Visual Studio to work with Selenium

  • Launch Visual Studio and start a new project
  • Select ‘Console Application' and name your project mySelenium


  • Next select Project>Add References from the tool bar and browser to the location where you extracted the Selenium dlls to. (Also be sure to select the correct version of .NET)


  • Select all the dlls and click ok


    Time to Code Selenium with C#!

    Cool!! Now that we have the Selenium dlls referenced in our project, it's time to test the configuration by running a quick test.

    At the top of your project code after the last ‘using' namespace add the following Selenium namespaces:

    using OpenQA.Selenium;
    using OpenQA.Selenium.IE;
    using OpenQA.Selenium.Support.UI;
    

    Add the following code in your static void main section:

    //!Make sure to add the path to where you extracting the IEDriverServer.exe:

    IWebDriver driver = new InternetExplorerDriver(@"C:\Download\IEDriverServer");
    driver.Navigate().GoToUrl("https://testguild.com/HpSupport.html");
    

    Your code should look like this:


    Run the test. joecolantonio.com should appear.

    How to Use the IE Developer Toolbar

    If you are going to be scripting against IE you'll want to install the Internet Explorer Developer Toolbar. (Those familiar with QTP are aware that this is similar QTP's spy tool)

    Using the IE Dev's Arrow feature allows you to spy on an element's attributes. You can then use those attributes in your Selenium code to help identify fields in you web application.


    For example if we want to navigate to www.joecolantonio.com/HpSupport.html and select a value from the ‘Select your tool & Version' we would point the IE Dev arrow to the field to see its attributes:


    Now that we know what the Id is, we can use that information to help Selenium interact with it. For example:

    myField = new driver.FindElement(By.Id("tools"));
    myField.SendKeys("QTP10");
    

    Run the test. It should start IE , navigate to http://www.joecolantonio/HPSupport.Html and select QTP10 from the Select your tool & version.

    Common Selenium IE issues to look out for

    If you getting the following error:

    InvalidOperationException was unhandled – unexpected error launching Internet Explorer. Protected Mode setting are not the same for all zones.

    Enable Protected Mode must be set to the same value (enabled or disabled) for all zones


    In IE tools>Internet Options>Security tab, make sure all your zones are set to the same value:


If you are getting the following error:

DriverServiceNotFoundException was unhandled: The file … \IEDriverServer.exe does not exist. The driver can be downloaded at


Make sure that you downloaded the IEDriverServer.exe and also that you have the correct path specified in your code

IWebDriver driver = new InternetExplorerDriver(@"C:\YourPath\IEDriverServer");

Good Luck, and happy Selenium IE an C# scripting!

Also be sure to check out tips and tricks on working with Selenium with IE with the creator of the SeleniumIE driver himself Jim Evans:

https://testguild.com/28-jim-evans-secrets-on-how-to-succeed-with-selenium-and-ie/

83 responses to “Selenium 2.0 WebDriver with Visual Studio, C#, & IE – Getting Started”

  1. Thanks a million mate. wasnt able to find any tutorial small and precise to get it working for chrome. this IE implementation did the job for me. thanks again mate. cheers.

  2. hi joe thanks for the tutorial .actually i need your help ,i’m using selenium webdriver with visual studio c# chrome driver ,i added the selenium references and installed the chrome driver but i cannot add it as reference.

    • Engy » Hi are you getting an error message? I just verified that it worked for me. Did you verify that in your project>references that you have all the selenium dlls added? Also make sure that you added the name space namespace OpenQA.Selenium.Chrome. For the chrome driver you need to either have the path to it in your machines PATH environment variable or add it as an argument when you instantiate the Chrome Driver:

      IWebDriver driver = new ChromeDriver(@”C:\pathToTheDriver\chromedriver\”);

  3. Thanks so much Joe. Simple and it’s work.. Awesome!!
    Now I can start the scripting with IE.

    Thanks again.. :)

  4. Hi Joe. Thanks for this page.
    I am a QTP prof. I m completely new to Selenium. I am good with C#, but not that much with Java.
    I find, that most of Selenium frameworks, like TestNG and ReportNG, are aligned to Java. But could not find as such for C#.
    People say, NUnit and MBUnit aren’t that handy. Also, no reporting framework is available.
    Do I need to learn Java all from scratch, or there are ways in C#? Please suggest. Thanks in advance !

  5. Hi Joe, in addition to my last post, I would like to know something. Might be a stupid question. Why do we need to integrate Selenium codes with unit testing frameworks ?? In QTP, we do not use 1.
    I understand, NUnit/JUnit uses assert functions. Is this the only use? I went through TestNG documentation, but couldn’t grab much. Can you please elaborate?

  6. please help me its not working as i have done all you guided …
    issue is that when i am running the code iside visual studio it give an error that “visual studio can not start dbugging because the debug target is missing. please buid the project and retry, or set the outpput path and assembly name properties appropriately to point on correct location for target assembly” how to fix it??

      • Hi,
        I got over it. Record with selenium ide, export to c#, and change the driver to IE.

        Now, reports sucks. I use c# and visual studio.
        Any suggestions on how to nicely report?

  7. Great info, as usual!

    I did something a little different, where I was creating it as a Test Project and going from there. I’m stuck on trying to write out my results to a notepad file though, but that’s another topic I suppose :-)

  8. Great guide for beginners

    How about handling the IE DriverServer.exe based on the IE bit information(32 or 64).

    any ideas are most welcome.

  9. Great work Joe with OpenSource! As it says OpenSource one mind set is to have Java in place, but i have to say you have given confidence to all microsoft dev’s :) — I also feel lil more tuts on C # with web testing would help us.

    Appreciate all your help.

  10. hi joe
    i am facing a problem in webdriver 2.0 + iedriver + c# that when i navigate to a url from try block it works fine but when i am trying same url to navigate after returning from catch block it takes very long time as long as 5 mins . navigation performs in background and all my lines below that navigation line executes in same time, please give me advice what to do. i had started using iedriver by seeing this post please help me
    class testclass
    {
    private readonly IWebDriver generalCourse;
    public testclass(IWebDriver driver)
    {
    weddriverobj= driver;
    }
    public bool foryourrefrence()
    {

    bool condition = true;
    int cnt = 0;
    while (condition)
    {
    try
    {
    if (cnt > 0)
    {

    weddriverobj.Navigate().GoToUrl(“http://www.google.com”);//replacing google with my test site
    weddriverobj.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

    }
    if (cnt == 0)
    {
    //clicking on another link for genrating error
    weddriverobj.FindElement(By.XPath(Object.doc_link)).Click();
    }

    //because another link is clicked this element will not be found
    weddriverobj.FindElementOnPage(By.XPath(Object.gereralcourse_link));
    weddriverobj.FindElement(By.XPath(Object.gereralcourse_link)).Click();

    condition = false;
    }
    catch (Exception ex)
    {
    if (cnt > 3)//tries 3 times for handling error
    {
    return false;
    }

    condition = true;//untill condition is true we will try
    cnt++;

    }

    }

    return true;
    }
    }

  11. Hey Joe,
    Thanks for the tutorial and it’s perfect to get me started (longtime QTP vet but new to selenium.) One question/problem though; when I add the lines:
    myField = new driver.FindElement(By.Id(“tools”));
    myField.SendKeys(“QTP10”);

    I get two runtime errors when running.
    Error 4 The type or namespace name ‘driver’ could not be found (are you missing a using directive or an assembly reference?)
    Error The name ‘myField’ does not exist in the current context

    Any Idea what I could be doing wrong?

      • Hey, Thanks much for this post, it was very helpful in setting me up for using selenium with C#. Really made things clear!
        The lines :
        myField = new driver.FindElement(By.Id(“tools”));
        myField.SendKeys(“QTP10″);

        I have entered as
        IWebElement myField = driver.FindElement(By.Id(“tools”));
        myField.SendKeys(“QTP10”);

        That’s the code listed in the video, which works, but the code listed on the site is different.

        Either way, thank you for the post!

  12. First of all – I’m a tester with some development experience, not a developer. My questions may seen a bit basic…bear with me.

    I finally got this to work once I created a console application and not a Web application – duh. I have a couple of questions:

    1. I can use driver.close() to close the web session, however it appears the console is still open. Is there a similar way to close it?

    2. I’ll need to also support testing in Firefox and Chrome. There is a Chrome driver available, however I believe the FF driver is included with Web Driver. I haven’t tried it yet. I’m assuming the process is the same for Chrome? What about Firefox?

    Thanks!
    Dave

  13. Hi Joe,

    I stumbled over your excellent tutorial on Selenium on trying to get Selenium to work with Silverlight. Are you able to shed light on how this can be achieved? I have scoured the interweb for ideas but info seems wither lacking or the examples do not work.

    Many thanks

    GrumpyTester

  14. Hi, grate tip:) i have a problem in last line of code: driver.FindElement(By.Id(“submit”)).Click(); how can a click submit button to login

    IWebDriver driver = new InternetExplorerDriver(@”C:\IEDriverServer_Win32_2.39.0″);
    driver.Navigate().GoToUrl(“http://localhost:4444/”);
    IWebElement myField = driver.FindElement(By.Id(“UserName”));
    myField.SendKeys(“admin”);
    IWebElement myField1 = driver.FindElement(By.Id(“Password”));
    myField1.SendKeys(“qwe123”);
    IWebElement myField3 = driver.FindElement(By.Id(“submit”)).Click();

  15. Joe,

    This is great but I have one problem, my test failed when checking page title. This due to the IEWebDriver displays then following when open the IE browser opens:

    “This is the initial start page for the WebDriver server.”

    Once my target URL is used, it then fails checking page title as it captures the initial start page title.

    Plus no dos prompt is shown when executing script.

    I am using Windows 7 with IE 10 with the latest Selenium WebDriver as from today. Any ideas?

  16. Hi, i am from China, your solution is awesome, thank you so much!!!! :) :) Keep in touch, ok? i am the beginner for selenium 2.

  17. Joe, this tutorial was excellent and worked well. I was able to setup and and apply to my own AUT. Thank-you! However.the dev tools “Select Element’ did not return the ‘ID’ atribute for a specific menu item I wanted to automate. For example :IED.findElement(By. … does not include an innerhtml object or method. How can I code to return an innerhtml where the innertext = Report

  18. Hi Joe,

    In my project we are facing an issue with silverlight object. I reached a lot but not found anything. Please help me we are using selenium with c#.

    Thanks

  19. Hi Joe,

    It was a wonderful tutorial from your side for selenium with C#, as there is very less help available online regarding this. I really appreciate the step taken by you to share your knowledge with others.

    I am my self a Automation Developer and currently using Selenium and c# for doing automation with Nunit.

    I am facing problem with respect to Selenium Grid implementation using c# specially for IE browser.

    I have somehow managed to run successfully multiple test on other browsers on different virtual machines, but i am facing problem while instantiating IE browser.

    I am pasting the code below please have a look

    C# Code
    if(browser == “iexplore”)
    {

    ////
    DesiredCapabilities dc = new DesiredCapabilities();

    dc = DesiredCapabilities.InternetExplorer();
    dc.SetCapability(“ie.binary”, “C:\Program Files (x86)\Internet Explorer\iexplore.exe”);

    dc.SetCapability(CapabilityType.BrowserName, “iexplore”);

    dc.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Vista));
    dc.SetCapability(CapabilityType.Version, “8.0”);
    try
    {
    Instance = new RemoteWebDriver(new Uri(“http://MachineIP:4444/wd/hub”), dc);
    }

    Also please find the code for selenium node

    java -jar selenium-server-standalone-2.42.1.jar -role webdriver -hub http://MachineIPName:4444/grid/register -port 7777 -maxInstances 20 -browser browserName=iexplore,version=8.0,platform=VISTA -Dwebdriver.ie.driver=IEDriverServer.exe

    Kindly let me know if i am doing anything wrong in the above code.

    I am not getting any specific error message, only “InvalidOperationException” and it states “The error did not contain a message”

    Internet Explorer opens and then it stops at the startup page

  20. Hi Joe, Thanks a lot for this quick help. I was able to run the code using bing.com. How ever I am getting timeout exception when running the code using a https site in IE. Example (https://facebook.com). Any idea what should be done for this?

  21. Hi Joe,
    I need your help. I want to generate reports for my test scripts.
    I am using Nunit and using C# language.
    Please tell me how to generate reports.

  22. Hello Joe,

    This is an awesome tutorial to get started. Thanks for the ignition.
    Well, i have a question. I created a folder in my project Driver and placed the IEDriverServer there. Now how can i give the path in my test script. Please help

  23. We have been using selenium web driver with C# since year, we execute our scripts on server machine (Windows server-2008 R2),

    From last month, our most of the test scripts are getting failed on Firefox 26 and showing below error.

    OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL http://localhost:7055/hub/session/4d7a575e-085b-4254-83d3-822f41f989e2/element/%7B2046f4e9-f39f-4ac5-8193-e53b1e5b8b05%7D/click timed out after 120 seconds. —-> System.Net.WebException : The operation has timed out

    We are getting this error on login method.

    Same script working fine when we debug or execute individually. Also scripts running fine on chrome browser.

    Selenium: 2.44
    OS: Windows Server 2008 R2
    Browser: Firefox 26

    Could please help/suggest us to resolve this issue.

  24. Thanks for the awesome tutorial. The first time I ran it, everything worked as expected. As I started to add code to create a config file, I kept getting the “NoSuchElementException” error.

    I figured that maybe I messed something up, so I scrapped the project and followed the tutorial again. I am still getting the “NoSuchElementException” error. In VS, if I explore the driver, I can see that it has the full page source, so the data is getting to the driver, but I don’t know what to do at this point. Any ideas?

  25. Thanks dude!!!

    The open org trolls couldn’t come up with something this easy to understand even if they had Watson on their side. They need to do less coding and more documenting.

  26. to avoid DriverServiceNotFoundException, IEDriverServer.exe should be somewhere in path or debug folder of your project.

    to avoid Protected Mode setting exception, initiate driver like this:
    InternetExplorerOptions options = new InternetExplorerOptions();
    options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
    driver = new InternetExplorerDriver(options);

    • Thanks Marius. Do you use the protected mode code approach in your tests? I thought I’ve seen multiple times in the different Selenium forums where Jim Evans the maintainer of the Selenium IEDriver does not recommend this approach.

  27. I spent about 50 mins hunting before finding this to-the-point tutorial. Information well put, very helpful.

  28. This is v handy stuff r beginners,gr8.joe can you help with some code to xecute test cases from excel file.
    Thanks

  29. Hi Joe,

    I have a script with multiple test cases. Here is the functionality –

    The script opens up a URL, login, logout and then close the browser and again same process for 2nd test case and so on.

    while running the script, URL is getting opened but login credentials are not getting entered and without closing the browser, second instance of the browser for next test case is getting opened.

    Can you please help me with this?
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

selenium ie