• Jobs
  • About
  • Getting started with Selenium 2 and WebDriver August 29, 2011

    Download Selenium 2

    To begin adding Selenium to your project, you will have to first download Selenium for the language you develop your framework on.

    The download comes as a zip file so you will first have to unzip it. In this unzipped folder contents, you will see selenium-java-2.x.y.jar and several other dependent jar files in the lib directory. Assuming you have a java development environment with the setup similar to the one defined in the Creating your Java project workspace post, you will have to copy these jar files in your lib directory as well. Most people just copy all the jars over, however, I recommend copying just the libraries you need.

    Starting and stopping Selenium server

    For those who have used earlier versions of Selenium, you are probably familiar with starting and stopping selenium using ant. In Selenium 2, you don’t need to start the server. Infact, the selenium-java-2.x.y.jar cannot be used to start the server in the first place. You need a separate jar to start the selenium 2 server, which is used only when you need to run Selenium 1 APIs on Selenium 2.

    Selenium-backed WebDriver

    For reasons described in the Selenium 2 introduction, if you plan to use the selenium server you will need to download the selenium-server-2.x.y.zip instead of the selenium-java-2.x.y.jar. You can find the selenium-server-2.x.y.zip on the Selenium project download google page.

    Instantiating WebDriver

    WebDriver is an interface in the new Selenium 2 API. The different implementations of this WebDriver interface allows programmatically controlling different browsers.

    Using the interface you could start a new browser instance, navigate to a url and close the browser using this snippet.

    WebDriver driver;
    Wait wait;
    
    public void instantiateBrowser(BrowserType browserType, String url) {
        driver = getWebDriver(browserType);
        wait = new WebDriverWait(driver, 30);
        driver.get(url);
    }
    
    public void closeBrowser() {
        driver.close();
    }
    
    public WebDriver getWebDriver(BrowserType browserType) {
        switch (browserType) {
            case FIREFOX:
                // Need to implement
                return null;
            case IE:
                // Need to implement
                return null;
            case CHROME:
                // Need to implement
                return null;
            case HTMLUNIT:
                // Need to implement
                return null;
            default:
                throw new RuntimeException("Browser type unsupported");
        }
    }
    
    public enum BrowserType {
        FIREFOX, IE, CHROME, HTMLUNIT
    }
    

    The following sections shows how you can instantiate and configure each browser type:

    Firefox

    In Firefox, it is recommended to create a firefox profile for test automation. I have an entire post dedicated to describing the steps to create a firefox profile.

    Once you have created this profile, you can instantiate a new firefox session using this code snippet.

    File profileDirectory = new File(profileDirectory);
    FirefoxProfile profile = new FirefoxProfile(profileDirectory);
    return new FirefoxDriver(profile);
    

    Here profileDirectory is the path to the directory where the profile is created.

    Internet Explorer

    With IE the first challenge I encountered was with security. The error you would get is:

    org.openqa.selenium.WebDriverException: Unexpected error launching Internet Explorer. Protected Mode must be set to the same value (enabled or disabled) for all zones.

    There are two ways to solve this:

    The first option is that in your Internet Explorer browser set the protected mode enabled or disabled for all zones (Internet, Local Intranet, Trusted Sites and Restricted sites). The problem with this option is that if you are testing a system which does not work with this security setting or you do not have control over the machines where your test code will execute, then you cannot use this approach.

    The second option to get around it is by using the INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS capability. You can set this capability by using the following snippet:

    DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
    ieCapabilities.setCapability(
            InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
    return new InternetExplorerDriver(ieCapabilities);
    

    The problem with this option is that there is a potential that you might get some flakiness/ unreliability while performing certain actions in IE. I haven’t encountered this flakiness yet though.

    Chrome

    With Chrome, you will have to download the chrome driver first. If you don’t you will see the error:

    java.lang.IllegalStateException: The path to the chromedriver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://code.google.com/p/chromium/downloads/list

    I recommend downloading all three binaries maintained by the Chromium project i.e. for windows, linux and mac and renaming them to chromedriver-win.exe, chromedriver-lin and chromedriver-mac. This way you can refer to them on the appropriate OS using the following code.

    DesiredCapabilities chromeCapabilities = DesiredCapabilities.chrome();
    
    String chromeBinary = System.getProperty(" ");
    if (chromeBinary == null || chromeBinary.equals("")) {
        String os = System.getProperty("os.name").toLowerCase().substring(0, 3);
        chromeBinary = "lib/chromedriver-" + os + (os.equals("win") ? ".exe" : "");
        System.setProperty("webdriver.chrome.driver", chromeBinary);
    }
    
    return new ChromeDriver(chromeCapabilities);
    

    One of the things that threw me off initially when I was looking for the binaries of the chrome driver was that I saw a linux 32 and 64 bit binary, but I only saw a win32 bit binary. I wondered if that meant that win64 was not supported. However, when I used the win32 binary on my windows 64bit machine, it worked.

    One other thing to keep in mind is that if you do not have Chrome installed in the default location, you could also tell WebDriver where to look for it by adding

    chromeCapabilities.setCapability("chrome.binary", "/path/to/where/chrome/is/installed/chrome.exe");

    before creating a new instance of the ChromeDriver.

    Posted by Rahul Poonekar in : Selenium

    17 Responses to “Getting started with Selenium 2 and WebDriver”

    1. Yeshwant says:

      Referring to section Internet Explorer, I am writing scripts in C#. I am not able to troubleshoot with the same. Any help in this regards?
      Thank you,
      Yesh

    2. Rahul Poonekar says:

      Can you share your script and the problem you are seeing?

    3. Yeshwant says:

      Thanks for the reply.
      I am using Visual Studio Express Edition.
      Script and Error ( as in Comments):
      ———————————————————
      using System;
      using System.Collections.Generic;
      using System.Collections.ObjectModel;
      using System.Text;
      using System.Threading;
      using OpenQA.Selenium;
      using OpenQA.Selenium.IE;
      using OpenQA.Selenium.Firefox;
      using OpenQA.Selenium.Chrome;
      using OpenQA.Selenium.Remote;
      using NUnit.Framework;

      namespace Selenium2Example
      {
      public class Test_Google
      {
      IWebDriver driver;
      public void Setup()
      {
      driver = new InternetExplorerDriver();
      //driver = new FirefoxDriver();
      driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 15));
      }

      public void Teardown()
      {
      driver.Quit();
      }

      public void TestGoogle()
      {

      IWebElement textBox, sLink, sLabel, sListValue, sButton;

      driver.Navigate().GoToUrl(“http://xyz.com”); // I have not provided the exact URL as it cannot be accesssed outside of the network

      textBox = driver.FindElement(By.Id(“username”)); // << Script errors out here… and display NoElementFoundException…..Tried to insert InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS but was not identifying…..
      textBox.SendKeys("XAdmin");

      }

      public static void Main()
      {
      Test_Google TG = new Test_Google();
      TG.Setup();
      TG.TestGoogle();
      TG.Teardown();
      }
      }
      }

    4. Rahul Poonekar says:

      Yeshwant, when I replaced your TestGoogle method with

              public void TestQAA()
              {
                  driver.Navigate().GoToUrl("http://referencewebapp.qaautomation.net/");
      
                  driver.FindElement(By.Id("username")).SendKeys("guest");
                  driver.FindElement(By.Id("password")).SendKeys("foobar");
                  driver.FindElement(By.Name("submit")).Click();
      
                  String s = driver.FindElement(By.ClassName("confirmation")).Text;
                  Console.WriteLine("Confirmation message: " + s);
                  Assert.AreEqual("Username/ password not found.", s);
              }
      

      it just worked for me. Can you give it a shot?

    5. bharath says:

      Hi ,this is useful guide to run chrome driver.

      Thanks,

    6. lethalduck says:

      Hi. I’m having trouble with my C# code around the chromedriver.exe
      I’ve got selenium-server-standalone-2.12.0.jar running on a VM.
      This is where chrome is targeted.
      It runs fine if I test against chrome on local machine, but not against chrome on an external machine.
      The error I’m getting:
      WARN – Exception: The path to the chromedriver executable must be set by the webdriver.chrome.driver system property

      The line that spits is…

      webDriver = new RemoteWebDriver(hostServerDetail.Uri, hostServerDetail.Capabilities);

      webDriver is a IWebDriver.
      The Uri looks like…
      “http://:4444/wd/hub”

      Capabilities looks like…
      DesiredCapabilities.Chrome()

      Any ideas?

    7. Tetiana says:

      And here the option how to add plugin to test Firefox Profile.
      1. Download plugin to your disk in advance, for example Firebug
      firebug-1.7.3-fx.xpi
      2. Use code like:
      File ext = new File(“firebug-1.7.3-fx.xpi”);
      FirefoxProfile profile = new FirefoxProfile();
      if (ext.exists()) {
      profile.addExtension(ext);
      profile.setPreference(“extensions.firebug.currentVersion”, “1.7.3″); //avoid startup screen
      profile.setPreference(“extensions.firebug.console.enableSites”, true); //enable console
      }

      //some more prefs:
      profile.setPreference( “app.update.enabled”, false);
      profile.setPreference( “browser.tabs.autoHide”, true);

      //use this profile:
      DesiredCapabilities capability = DesiredCapabilities.firefox();
      capability.setCapability(FirefoxDriver.PROFILE, profile);

      //run driver with this profile this profile:
      RemoteWebDriver driver = new RemoteWebDriver(capability);

    8. Ade says:

      Thanks for the code but the problem i’m having is that it keeps failing at configuration. It states that – Method getWebDriver requires 1 parameters but 0 were supplied in the @Configuration annotation. Below is a snippet of my code –

      @BeforeTest(alwaysRun=true)

      public WebDriver getWebDriver(BrowserType browserType){

      switch(browserType){
      case FIREFOX:
      //Implement firefox browser
      File file = new File(“/Users/automation/Library/Application Support/Firefox/Profiles/tiaz0uew.Webdriver”);
      FirefoxProfile profile = new FirefoxProfile(file);
      //driver = new FirefoxDriver(profile);
      return new FirefoxDriver(profile);
      case IE:
      //
      return null;
      case CHROME:
      //Implement chrome browser
      DesiredCapabilities capabilities = DesiredCapabilities.chrome();
      capabilities.setCapability(“chrome.binary”, “/applications/Google Chrome.app”);
      System.setProperty(“webdriver.chrome.driver”,”/Users/automation/__@dev/chromedriver”);
      //driver = new ChromeDriver();
      return new ChromeDriver();
      case HTMLUNIT:
      //
      return null;
      default:
      throw new RuntimeException(“Browser type unsupported”);

      }

      }
      public void instantiateBrowser(BrowserType browserType) throws Exception{

      driver = getWebDriver(browserType);
      wait = new WebDriverWait(driver, 30);
      //driver.get(url);

      }

      public void setUp() throws Exception{

      instantiateBrowser(BrowserType.FIREFOX);
      }

      @AfterTest(alwaysRun=true)

      public void tearDown() throws Exception {

      if (driver!= null) {

      driver.quit();

      }
      }

      public enum BrowserType{

      FIREFOX, IE, CHROME, HTMLUNIT;
      }

      public void goToURL(String location) throws Exception {

      String url;
      url = getURL(location);

      selenium = new WebDriverBackedSelenium(driver,url);

      //Open the browser, maximize the window and put focus on it
      selenium.open(“/”);
      selenium.windowMaximize();
      selenium.windowFocus();
      selenium.waitForPageToLoad(“30000″);

      }

      Thanks for your help

    9. Reaz says:

      Really nice example of using different driver instance. I am having trouble to execute this test using ANT as i am taking the browser instance on runtime from user and plug it to code from system property. But seeing issue on Chromedriver. Keep getting “The path to the chromedriver executable must be set by the webdriver.chrome.driver system property” error. I tried creating chrome driver with chrome path and with capabilities but still reeving error. Any solution will be appreciated.

      Thanks
      Reaz

    10. Jilna says:

      Can you please help out on how to run the test on Chrome and IE using Selenium Server. Being trying since a long time but unsuccessful every time. Can you please put down the steps that are to be followed for running the test using the server?

      Thank You !

    11. satish says:

      Can some one give me Selenium 2 with java and testng Automation test framework for download. As I am looking for working with web driver

    12. Pooja says:

      Hi,
      I’m working with Selenium WD and VS Express Edition (C#).
      I’m looking for a way of how to assert the test case using Assert.
      The scenario is that I’ve searched for a person on my company portal. Now i need to assert this test case. how do i do it??
      Is it something like i need to count the no. of rows of the result n check to see if its one or more than one? Or is there any other way to assert it?
      Thank u in advance..

    13. swati says:

      Hi,
      I am new to testing. Recently I have completed Diploma in Software Testing. Actually i am from electronics background.
      I am quite familiar with C, VB, HTML and sql. I dont know anything about C++, or java.
      I want to learn webdriver. I know basics of Selenium 1. Is it possible for me to start with webdriver? What can i do?

      Please reply.

    14. Subrat says:

      Hi,
      I was just wondering which is the latest jar to use for Internet Explorer Webdriver.
      I am unable to proceed. Please help.

    15. yedukondalu says:

      hi swati,

      u want learn webdriver 1) we can do java fundamentals after we learn webdriver.

    16. Anshu says:

      I have created one sample program in java which is basically importing input from a xls file and then running the script.
      It is working fine when i run this using junit.Now I want to execute this code with the help of command prompt.
      Can someone please guide me how i will do it?

      I have install ant as well but not able to run this code.

      package com.testing;
      import java.io.FileInputStream;
      //import java.io.IOException;
      import jxl.Sheet;
      import jxl.Workbook;
      import org.junit.After;
      import org.junit.Before;
      import org.junit.Test;
      import org.openqa.selenium.By;
      import org.openqa.selenium.WebDriver;
      import org.openqa.selenium.firefox.FirefoxDriver;
      public class Data{
      Sheet s;
      WebDriver driver;
      @Before
      public void setUp()
      {
      driver = new FirefoxDriver();
      }
      @Test
      public void searchGoogle() throws Exception
      {
      FileInputStream fi = new FileInputStream(“C:\\Users\\akhandelwal\\Documents\\Test.xls”);
      Workbook w = Workbook.getWorkbook(fi);
      s = w.getSheet(0);
      for(int row=1; row <=s.getRows();row++)
      {
      String username = s.getCell(0, row).getContents();
      System.out.println("Username "+username);
      driver.get("http://www.gmail.com&quot;);
      driver.findElement(By.name("Email")).sendKeys(username);
      String password= s.getCell(1, row).getContents();
      System.out.println("Password "+password);
      driver.findElement(By.name("Passwd")).sendKeys(password);
      driver.findElement(By.name("signIn")).click();
      }
      }
      @After
      public void tearDown()
      {
      driver.close();
      driver.quit();
      }
      }

    Leave a Reply