Selenium 2

To the perfect testing framework for web applications.

The api is located at http://webdriver.googlecode.com/svn/javadoc/index.html?overview-summary.html http://selenium.googlecode.com/svn/trunk/docs/api/java/index.html

What are new: -Merge the best of Selenium and Webdriver. -Complete change of the api. -Bundle into a standalone jar.

Note: By default, Javascript for HtmlUnitDriver is disabled. Use setJavascriptEnabled() to enable like the following:

HtmlUnitDriver driver = new HtmlUnitDriver();
driver.setJavascriptEnabled(true);

First Selenium 2 application in Java

For similar example using Selenium v1, see First Selenium application in Java.

The following shows you step-by-step how to run your first Selenium 2 application in Java.

  1. It is assumed that you have JDK installed and set in your computer. If you are getting the version number(e.g javac 1.6.0_06) by running the following command in the Command Prompt, then your Java Compiler is installed and set correctly.
    javac -version
  2. Download selenium-server-standalone-2.0a5.jar and save it to c:\.
  3. The Google2.java file containing the Java code below is our first Selenium 2 application. What the code does is to launch Internet Explorer, open Google webpage and then search for Selenium 2.
    /**
     * Google2.java
     * Open Google webpage and search for "Selenium 2".
     * @Author: Xuan Ngo
     */
    import org.openqa.selenium.ie.InternetExplorerDriver;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
     
    public class Google2
    {
      public static void main(String[] args)
      {
        final String sUrl = "http://www.google.ca/index.html";
     
        // Instantiate the Internet Explorer browser.
        WebDriver oWebDriver = new InternetExplorerDriver();
     
        // Open the main google webpage.
        oWebDriver.get(sUrl);
     
        // Get the search input html element.
        WebElement oSearchInputElem = oWebDriver.findElement(By.name("q")); // Use name locator to identify the search input field.
     
        // Type "Selenium 2" into the search input field.
        oSearchInputElem.sendKeys("Selenium 2");
     
        // Get the Google Search button.
        WebElement oGoogleSearchBtn = oWebDriver.findElement(By.xpath("//input[@name='btnG']"));
     
        // Click on "Google Search" button
        oGoogleSearchBtn.click();
     
        // Pause for a few seconds so that you can see the result before closing the browser.
        try
        {
          Thread.sleep(5000);
        }
        catch(InterruptedException ex)
        {
          System.out.println(ex.getMessage());
        }
     
        // Close the browser.
        oWebDriver.close();
      }
    }
    Execute the command below to compile the Java code.
    javac -classpath C:\selenium-server-standalone-2.0a5.jar Google2.java
    Note: You have to change C:\selenium-server-standalone-2.0a5.jar to match the path where you put your selenium-server-standalone-2.0a5.jar.
  4. Execute the command below to run our application.
    java -classpath C:\selenium-server-standalone-2.0a5.jar;. Google2
    Note: You have to change C:\selenium-server-standalone-2.0a5.jar to match the path where you put your selenium-server-standalone-2.0a5.jar.
AttachmentSize
File Google2.java1.36 KB

Add Selenium jar file in Eclipse

Add Selenium jar file in Eclipse

  1. Import selenium library into your project.
  2. Right-click on your project and navigate to Build Path->Configure Build Path....
  3. On the Libraries tab, click on the Add JARs... button and select selenium jar file.

Click on link

For similar example using Selenium v1, see Click on link.

/**
 * Selenium v2: Click on a simple link(e.g Next)
 * Assume that you have Internet Explorer.
 * @Author: Xuan Ngo
 */
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
 
public class ClickExample
{
  public static void main(String[] args)
  {
    // All actions will be applied to Internet Explorer
    WebDriver oWebDriver = new InternetExplorerDriver();
 
    // Open the webpage.
    oWebDriver.get("http://openwritings.net/sites/default/files/clickLinkTest.html");
 
    // Find and click on the Next link.
    WebElement oClickElem = oWebDriver.findElement(By.linkText("Next")); // Find Next link.
    oClickElem.click(); // Click on the element found(i.e. Next).
 
    // Pause so that you can see that Selenium has clicked.
    pause(5000);
 
    // Close the browser.
    oWebDriver.close(); 
  }
 
  /**
   * Pause for X milliseconds.
   * @param iTimeInMillis
   */
  public static void pause(final int iTimeInMillis)
  {
    try
    {
      Thread.sleep(iTimeInMillis);
    }
    catch(InterruptedException ex)
    {
      System.out.println(ex.getMessage());
    }
  }
 
}

Install and Setup Webdriver

Chrome Webdriver

  1. Go to http://chromedriver.storage.googleapis.com/index.html and download the lastest version of chromedriver.
  2. Extract the driver and put it in your environment variable.

Click on any html element using different locators

For similar example using Selenium v1, see Click on any html element using different locators.

/**
 * Selenium v2: Click on any html element in the webpage as long as you can use the locators to identify them.
 * Assume that you have Internet Explorer.
 * @Author: Xuan Ngo
 */
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
 
public class ClickAnyElementExample
{
  public static void main(String[] args)
  {
    // All actions will be applied to Internet Explorer
    WebDriver oWebDriver = new InternetExplorerDriver();
 
    // Open the webpage.
    oWebDriver.get("http://openwritings.net/sites/default/files/ClickAnyElementExample.html");
 
    WebElement oClickElem = null;
 
    // Using name locator: Find and click on the Next link.
    oClickElem = oWebDriver.findElement(By.name("submit_button")); // Find Next link.
    oClickElem.click(); // Click on the element found(i.e. Next).
    pause(1000); // Pause so that you can see that Selenium had clicked.
 
    // Using ID locator: Find and click on the Next link.
    oClickElem = oWebDriver.findElement(By.id("unique-link-id")); // Find Next link.
    oClickElem.click(); // Click on the element found(i.e. Next).
    pause(1000); // Pause so that you can see that Selenium had clicked.
 
    // Using XPATH locator: Find and click on the Next link.
    oClickElem = oWebDriver.findElement(By.xpath("//li[contains(text(), 'using the xpath')]")); // Find Next link.
    oClickElem.click(); // Click on the element found(i.e. Next).
    pause(3000); // Pause so that you can see that Selenium had clicked.
 
    // Close the browser.
    oWebDriver.close(); 
  }
 
  /**
   * Pause for X milliseconds.
   * @param iTimeInMillis
   */
  public static void pause(final int iTimeInMillis)
  {
    try
    {
      Thread.sleep(iTimeInMillis);
    }
    catch(InterruptedException ex)
    {
      System.out.println(ex.getMessage());
    }
  }
 
}

Type characters

For similar example using Selenium v1, see Type characters.

import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
 
/**
 * Selenium v2: Type characters.
 * Assume that you have Firefox installed.
 * You need to change the encoding of your editor to support the Chinese characters below.
 * @Author: Xuan Ngo
 */
public class WritingExample2
{
  public static void main(String[] args)
  {
    // All actions will be applied to Firefox.
    WebDriver oWebDriver = new FirefoxDriver();
 
    // Open the webpage.
    oWebDriver.get("http://openwritings.net/sites/default/files/WritingExample.html");
 
    WebElement oInputElement = null;
 
    // Type characters using different locators and field types.
    oInputElement = oWebDriver.findElement(By.xpath("//*[@name='first-name']"));  // XPATH locator.
    oInputElement.sendKeys("Xuan");
 
    oInputElement = oWebDriver.findElement(By.cssSelector("input[name='last-name']"));  // CSS locator.(2010-05-30: IE driver doesn't support CSS locator.)
    oInputElement.sendKeys("Ngo");
 
    oInputElement = oWebDriver.findElement(By.className("red"));  // Class Name locator: the value of the "class" attribute.
    oInputElement.sendKeys("my password");
 
    oInputElement = oWebDriver.findElement(By.id("unique-id"));   // ID locator. Type Chinese characters. You need to change the encoding of your editor.
    oInputElement.sendKeys("中文");
 
    oInputElement = oWebDriver.findElement(By.name("key-press")); // Name locator.
    oInputElement.sendKeys("auto complete");
 
    pause(10000);
 
    // Close the browser.
    oWebDriver.close(); 
  }
 
  /**
   * Pause for X milliseconds.
   * @param iTimeInMillis
   */
  public static void pause(final int iTimeInMillis)
  {
    try
    {
      Thread.sleep(iTimeInMillis);
    }
    catch(InterruptedException ex)
    {
      System.out.println(ex.getMessage());
    }
  }
 
}
AttachmentSize
HTML icon WritingExample.html1.53 KB

Check radio buttons and checkboxes

For similar example using Selenium v1, see Check radio buttons and checkboxes.

/**
 * Selenium v2: Un/Check radio buttons and check boxes.
 * It is assumed that Firefox is installed on your computer.
 * @Author: Xuan Ngo
 */ 
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
 
public class CheckExample2
{
  public static void main(String[] args)
  {
    // All actions will be applied to Firefox.
    WebDriver oWebDriver = new FirefoxDriver();
 
    // Open the webpage.
    oWebDriver.get("http://openwritings.net/sites/default/files/radio_checkbox.html");
 
    // Radio Button: Check Monday using XPATH locator.
    WebElement oRadioBtn = oWebDriver.findElement(By.xpath("//input[@value='Mon']"));
    oRadioBtn.click();
 
    // Checkbox: Uncheck Apple using CSS selector.
    WebElement oCheckBoxApple = oWebDriver.findElement(By.cssSelector("input[name='apple']")); // 2010-06-01: IE Driver doesn't support cssSelector yet.
    oCheckBoxApple.click();
 
    // Checkbox: Check Orange using CSS selector.
    WebElement oCheckBoxOrange = oWebDriver.findElement(By.cssSelector("input[name='orange']")); // 2010-06-01: IE Driver doesn't support cssSelector yet.
    oCheckBoxOrange.click();    
 
    pause(10000); // Pause so that you can see the results.
 
    // Close the browser.
    oWebDriver.close(); 
  }
 
  /**
   * Pause for X milliseconds.
   * @param iTimeInMillis
   */
  public static void pause(final int iTimeInMillis)
  {
    try
    {
      Thread.sleep(iTimeInMillis);
    }
    catch(InterruptedException ex)
    {
      System.out.println(ex.getMessage());
    }
  }
 
}

Select single and multiple options

For similar example using Selenium v1, see Select single/multiple options.

import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
 
/**
 * Selenium v2: Select single and multiple options.
 * It is assumed that Firefox is installed on your computer.
 * @Author: Xuan Ngo
 */ 
public class SelectExample2
{
  public static void main(String[] args)
  {
    // Run all actions on Firefox.
    WebDriver oWebDriver = new FirefoxDriver();
 
    // Open the webpage.
    oWebDriver.get("http://openwritings.net/sites/default/files/select.html");
 
    /**
     *  Single Selection: Select July.
     */
    // Find <select> element of "Single selection" using ID locator.
    Select oSingleSelection = new Select(oWebDriver.findElement(By.id("single-selection")));
 
    // Select <option ...>July</option>
    oSingleSelection.selectByVisibleText("July");
 
    /**
     * Multiple Selections: Use variations of locators to select February, August and November.
     */
    // Find <select> element of "Multiple selection" using XPATH locator.
    Select oMulitpleSelection = new Select(oWebDriver.findElement(By.xpath("//select[@multiple='multiple' and @size=12]")));
 
    // Clear all selected entries.
    oMulitpleSelection.deselectAll();
 
    // Select February, August and November using different functions.
    oMulitpleSelection.selectByIndex(1); // February
    oMulitpleSelection.selectByValue("Aug"); // Select <option ... value="Aug">...</option>
    oMulitpleSelection.selectByVisibleText("November"); // Select <option ...>November</option>
 
    /**
     * Pause so that you can see the results.
     */
    pause(10000); 
 
    /**
     * Close the browser.
     */
    oWebDriver.close(); 
  }
 
  /**
   * Pause for X milliseconds.
   * @param iTimeInMillis
   */
  public static void pause(final int iTimeInMillis)
  {
    try
    {
      Thread.sleep(iTimeInMillis);
    }
    catch(InterruptedException ex)
    {
      System.out.println(ex.getMessage());
    }
  }
 
}

Overloading findElement() to add waiting time

Update: 2010-08-05: It looks like overloading findElements() to add a wait time is no longer required. As of version 2.0a5, you can use RemoteWebDriver.RemoteTimeouts.implicitlyWait() like the following:

driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS)


When you run the same test multiple times without changing any code, WebDriver sometimes fails to find elements. This may be caused by multiple factors such as the network connection speed, ajax, etc. For a detailed explanation, see here. Due to these problems, I decided to make findElement() more fault tolerant. Therefore, I overload findElement() to add a waiting time. It will keep waiting until the element is found or a timeout is expired.

/**
 * Before finding the element, keep waiting until the element is found or a timeout is expired.
 * @param webDriver
 * @param by
 * @param timeout Timeout in milliseconds.
 * @return Return the WebElement found.
 */
private WebElement findElement(WebDriver webDriver, By by, int timeout)
{
  int iSleepTime = 1000;
  for(int i=0; i<timeout; i+=iSleepTime)
  {
    List<WebElement> oWebElements = webDriver.findElements(by);
    if(oWebElements.size()>0)
    {
      return oWebElements.get(0);
    }
    else
    {
      try
      {
        Thread.sleep(iSleepTime);
        System.out.println(String.format("%s: Waited for %d milliseconds.[%s]", new java.util.Date().toString(), i+iSleepTime, by));          
      }
      catch(InterruptedException ex) 
      {
        throw new RuntimeException(ex);
      }
    }
  }
 
  // Can't find 'by' element. Therefore throw an exception.
  String sException = String.format("Can't find %s after %d milliseconds.", by, timeout);
  throw new RuntimeException(sException);    
}