First Selenium 2 application in Java

By xngo on February 22, 2019

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.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.