My favorites | Sign in
Logo
Project hosting will be READ-ONLY Wednesday at 8am PST due to brief network maintenance.
                
Search
for
Updated Nov 09, 2009 by simon.m.stewart
Labels: Featured, WebDriver
GettingStarted  
Getting started with WebDriver

The 5 Minute Getting Started Guide

WebDriver is a tool for automating testing web applications, and in particular to verify that they work as expected. It aims to provide a friendly API that's easy to explore and understand, which will help make your tests easier to read and maintain. It's not tied to any particular test framework, so it can be used equally well with JUnit, TestNG or from a plain old "main" method. This "Getting Started" guide introduces you to WebDriver's Java API and helps get you started becoming familiar with it.

Start by downloading the latest binaries and unpack them into a directory. From now on, we'll refer to that as $WEBDRIVER_HOME. Now, open your favourite IDE and:

  • Start a new Java project in your favourite IDE
  • Add all the JAR files under $WEBDRIVER_HOME to the CLASSPATH

You can see that WebDriver acts just as a normal Java library does: it's entirely self-contained, and you don't need to remember to start any additional processes or run any installers before using it.

You're now ready to write some code. An easy way to get started is this example, which searches for the term "Cheese" on Google and then outputs the result page's title to the console. You'll start by using the HtmlUnitDriver. This is a pure Java driver that runs entirely in-memory. Because of this, you won't see a new browser window open.

package org.openqa.selenium.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

public class Example  {
    public static void main(String[] args) {
        // Create a new instance of the html unit driver
        // Notice that the remainder of the code relies on the interface, 
        // not the implementation.
        WebDriver driver = new HtmlUnitDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());
    }
}

Compile and run it. You should see a line with the title of the Google search results as output. Congratulations, you've managed to get started with WebDriver!

In this next example, let's use a page that requires Javascript to work properly, such as Google Suggest. You will also be using the FirefoxDriver. Make sure that Firefox is installed on your machine and is in the normal location for your OS.

Once that's done, create a new class called GoogleSuggest, which looks like:

package org.openqa.selenium.example;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.RenderedWebElement;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GoogleSuggest {
    public static void main(String[] args) throws Exception {
        // The Firefox driver supports javascript 
        WebDriver driver = new FirefoxDriver();
        
        // Go to the Google Suggest home page
        driver.get("http://www.google.com/webhp?complete=1&hl=en");
        
        // Enter the query string "Cheese"
        WebElement query = driver.findElement(By.name("q"));
        query.sendKeys("Cheese");

        // Sleep until the div we want is visible or 5 seconds is over
        long end = System.currentTimeMillis() + 5000;
        while (System.currentTimeMillis() < end) {
            // Browsers which render content (such as Firefox and IE) return "RenderedWebElements"
            RenderedWebElement resultsDiv = (RenderedWebElement) driver.findElement(By.className("gac_m"));

            // If results have been returned, the results are displayed in a drop down.
            if (resultsDiv.isDisplayed()) {
              break;
            }
        }

        // And now list the suggestions
        List<WebElement> allSuggestions = driver.findElements(By.xpath("//td[@class='gac_c']"));
        
        for (WebElement suggestion : allSuggestions) {
            System.out.println(suggestion.getText());
        }
     }
}

When you run this program, you'll see the list of suggestions being printed to the console. That's all there is to using WebDriver!

Hopefully, this will have whet your appetite for more. In the NextSteps page, you will learn how more about how to use WebDriver. It covers aspects such as navigating forward and backward in your browser's history, how to use frames and windows and it provides a more complete discussion of the examples than has been done as you've been GettingStarted. If you're ready, let's take the NextSteps!


Comment by misha680, Jan 24, 2010

Alternate uses include automation of routine Web tasks. Here are some sample scripts for web sites eharmony and chemistry.com.

Eharmony new matches:

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.RenderedWebElement;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxDriver;

public class eh1new {
    public static void main(String[] args) throws Exception {
        WebDriver driver=new FirefoxDriver();
	driver.get("http://www.eharmony.com/login");
	driver.findElement(By.name("j_username")).sendKeys("username");
	driver.findElement(By.name("j_password")).sendKeys("password");
	driver.findElement(By.name("submit")).click();
	driver.findElement(By.linkText("My Matches")).click();
	driver.findElement(By.linkText("New")).click();
	try {
	    while (true) {
		try {
		    driver.findElement(By.linkText("View Match Details")).click();
		} catch (Exception e) {
		    e.printStackTrace();
		}
		try {
		    driver.findElement(By.linkText("Request my photo")).click();
		} catch (Exception e) {}
		driver.findElement(By.linkText("Send her a Message")).click();
		driver.findElement(By.name("chooseQuestionsButton.x")).click(); // Send Questions
		driver.findElement(By.linkText("Return to My Matches")).click();		
	    }	    
	} catch (Exception e) {
	    e.printStackTrace();
	}
	driver.quit();
    }
}

Eharmony active matches ("Guided Communication"):

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.RenderedWebElement;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxDriver;

public class eh2matches {
    public static void main(String[] args) throws Exception {
        WebDriver driver=new FirefoxDriver();
	driver.get("http://www.eharmony.com/login");
	driver.findElement(By.name("j_username")).sendKeys("username");
	driver.findElement(By.name("j_password")).sendKeys("password");
	driver.findElement(By.name("submit")).click();
	driver.findElement(By.linkText("My Matches")).click();
	driver.findElement(By.linkText("Communicating")).click();

	try {
	    while (true) {
		try {
		    while (true) {
			driver.findElement(By.linkText("Read \"Closed\" Message")).click();		
			driver.findElement(By.name("continueCloseButton.x")).click(); // Close Match
			driver.findElement(By.linkText("Return to My Matches")).click();		
		    }	    
		} catch (Exception e) {}
		
		try {
		    while (true) {
			driver.findElement(By.linkText("Send Must Haves & Can't Stands")).click();
			driver.findElement(By.name("ownerContinue.x")).click(); // Send
			driver.findElement(By.linkText("Return to My Matches")).click();
		    }
		} catch (Exception e) {}

		int match=0;
		try {
		    List<WebElement> matches=null;
		    do {
			matches=driver.findElements(By.className("name"));
			String name=matches.get(match).getText();
			driver.findElement(By.linkText(name)).click();
			try {
			    driver.findElement(By.linkText("Request my photo")).click();
			} catch (Exception e) {}
			try {
			    driver.findElement(By.className("nudge-button")).click();
			} catch (Exception e) {}
			driver.findElement(By.linkText("Return to My Matches")).click();
			match=match+1;
		    } while (match<matches.size());
		} catch (Exception e) {}

		driver.findElement(By.className("nextpage")).click();
	    }
	} catch (Exception e) {}

	driver.quit();
    }
}

Chemistry.com new matches:

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.RenderedWebElement;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ch1new {
    public static void main(String[] args) throws Exception {
        WebDriver driver=new FirefoxDriver();
	driver.get("http://www.chemistry.com/Login/Login.aspx");
	driver.findElement(By.name("loginPageView1$ctl00$GlobalLoginControl$ctl00$txtHandle")).sendKeys("username");
	driver.findElement(By.name("loginPageView1$ctl00$GlobalLoginControl$ctl00$txtPassword")).sendKeys("password");
	driver.findElement(By.name("loginPageView1$ctl00$GlobalLoginControl$ctl00$btnSubmitDB")).click();
	Thread.sleep(2000);

	try {
	    driver.findElement(By.id("myhome_ctl00_btnRefreshMatches")).click(); // get more matches
	    Thread.sleep(2000);
	} catch (Exception e) {}

	try {
	    while (true) {
		driver.findElement(By.xpath("//img[@alt='View Profile']")).click();
		Thread.sleep(2000);		
		driver.findElement(By.id("showProfilePageView_ctl00_showProfileRatingTop_ctl00_lnkAction0")).click(); // I'm interested
		Thread.sleep(2000);		
		driver.findElement(By.id("showProfilePageView_ctl00_showProfileMiniNavTop_ctl00_lnkNext")).click(); // next profile
		Thread.sleep(2000);
	    }	    
	} catch (Exception e) {}
	driver.quit();
    }
}

Chemistry.com Active Matches:

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.RenderedWebElement;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ch2active {
    public static void main(String[] args) throws Exception {
        WebDriver driver=new FirefoxDriver();
	driver.get("http://www.chemistry.com/Login/Login.aspx");
        driver.findElement(By.name("loginPageView1$ctl00$GlobalLoginControl$ctl00$txtHandle")).sendKeys("username");
        driver.findElement(By.name("loginPageView1$ctl00$GlobalLoginControl$ctl00$txtPassword")).sendKeys("password");
	driver.findElement(By.name("loginPageView1$ctl00$GlobalLoginControl$ctl00$btnSubmitDB")).click();
	driver.findElement(By.id("lnkAM")).click();

	try {
	    while (true) {
		boolean task;
		do {
		    task=false;
		    try {
			driver.findElement(By.partialLinkText("Begin")).click();
			driver.findElement(By.id("showProfilePageViewAM_ctl00_ShowProfileNextStepAMBottom_ctl00_ActionHyperlink")).click();
			task=true;
		    } catch (Exception e) {}
		    try {
			driver.findElement(By.partialLinkText("Send relationships essentials")).click();
			driver.findElement(By.id("showProfilePageViewAM_ctl00_ShowProfileNextStepAMBottom_ctl00_ActionHyperlink")).click();
			task=true;
		    } catch (Exception e) {}
		    try {
			driver.findElement(By.partialLinkText("Compare relationship essentials")).click();
			driver.findElement(By.id("showProfilePageViewAM_ctl00_ShowProfileNextStepAMBottom_ctl00_ActionHyperlink")).click();
			task=true;
		    } catch (Exception e) {}
		    try {
			driver.findElement(By.partialLinkText("Send short answer questions")).click();
			List<WebElement> elements=driver.findElements(By.xpath("//input[@type = 'checkbox']"));
			for (int i=0;i<6;i++) {
			    elements.get(i).click();
			}
			driver.findElement(By.linkText("Send Questions")).click();
			task=true;
		    } catch (Exception e) {}		
		    try {
			driver.findElement(By.partialLinkText("View short answer responses")).click();
			driver.findElement(By.id("showProfilePageViewAM_ctl00_ShowProfileNextStepAMBottom_ctl00_ActionHyperlink")).click();
			task=true;
		    } catch (Exception e) {}		
		    try {
			driver.findElement(By.linkText("Nudge her")).click();
			task=true;
		    } catch (Exception e) {}
		} while (task);
		driver.findElement(By.linkText("Next")).click();
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
	driver.quit();
    }
}

Enjoy!

Misha Koshelev misha 680 at gmail dot com

Comment by misha680, Jan 24, 2010

One more - clear out chemistry.com email. Enjoy!

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.RenderedWebElement;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ch3email {
    public static void main(String[] args) throws Exception {
        WebDriver driver=new FirefoxDriver();
	driver.get("http://www.chemistry.com/Login/Login.aspx");
        driver.findElement(By.name("loginPageView1$ctl00$GlobalLoginControl$ctl00$txtHandle")).sendKeys("username");
        driver.findElement(By.name("loginPageView1$ctl00$GlobalLoginControl$ctl00$txtPassword")).sendKeys("password");
	driver.findElement(By.name("loginPageView1$ctl00$GlobalLoginControl$ctl00$btnSubmitDB")).click();
	driver.findElement(By.partialLinkText("Email")).click();

	// Delete all
	driver.findElement(By.linkText("Sent")).click();
	try {
	    driver.findElement(By.id("inboxPageView1_ctl00_emailListingControl_ctl00_chkHead")).click();
	    driver.findElement(By.className("deleteLink")).click();
	    driver.findElement(By.id("inboxPageView1_ctl00_generalConfirmEmbeddedPopUp1_ctl00_popupYesLink")).click();
	} catch (Exception e) {}

	// Delete all
	driver.findElement(By.linkText("Trash")).click();
	try {
	    driver.findElement(By.id("inboxPageView1_ctl00_emailListingControl_ctl00_chkHead")).click();
	    driver.findElement(By.className("deleteLink")).click();
	    driver.findElement(By.id("inboxPageView1_ctl00_generalConfirmEmbeddedPopUp1_ctl00_popupYesLink")).click();
	} catch (Exception e) {}

	driver.quit();
    }
}

Misha Koshelev misha 680 at gmail dot com

Comment by misha680, Jan 25, 2010

Two more serious examples:

Empty Google Voice Trash:

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.RenderedWebElement;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxDriver;

public class gvtrashempty {
    public static void main(String[] args) throws Exception {
        // The Firefox driver supports javascript
        WebDriver driver=new FirefoxDriver();
	
        // Go to Google Voice
        driver.get("https://www.google.com/voice/");

	// Login
        driver.findElement(By.name("Email")).sendKeys("username");
        driver.findElement(By.name("Passwd")).sendKeys("password");
	driver.findElement(By.name("signIn")).click();

	// Go to Trash
        driver.get("https://www.google.com/voice/#trash");

	// Handle confirmation dialog
	// http://code.google.com/p/selenium/issues/detail?id=27&redir=1
	((JavascriptExecutor)driver).executeScript("window.confirm = function(msg){return true;};");

	try {
	    while (true) {
		// No items? we're done!
	        if (driver.getPageSource().contains("No items")) {
		    break;
		}
		
		// Checkbox
		driver.findElement(By.className("gc-menu-icon")).click();

		// Select all
		List<WebElement> menuitems=driver.findElements(By.className("goog-menuitem"));
		for (WebElement menuitem:menuitems) {
		    if (menuitem.getText().equals("Select all")) {
			menuitem.click();
		    }
		}		
		
		// Delete forever
		driver.findElement(By.id("gc-inbox-delete-forever")).click();
	    }
	} catch (Exception e) {
	}

	// quit
	driver.quit();	
    }
}

Empty Google Voice History:

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.RenderedWebElement;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxDriver;

public class gvhistoryempty {
    public static void main(String[] args) throws Exception {
        // The Firefox driver supports javascript
        WebDriver driver=new FirefoxDriver();
	
        // Go to Google Voice
        driver.get("https://www.google.com/voice/");

	// Login
        driver.findElement(By.name("Email")).sendKeys("email");
        driver.findElement(By.name("Passwd")).sendKeys("password");
	driver.findElement(By.name("signIn")).click();

	// Go to Trash
        driver.get("https://www.google.com/voice/#history");

	// Handle confirmation dialog
	// http://code.google.com/p/selenium/issues/detail?id=27&redir=1
	((JavascriptExecutor)driver).executeScript("window.confirm = function(msg){return true;};");

	try {
	    while (true) {
		// No items? we're done!
	        if (driver.getPageSource().contains("No items")) {
		    break;
		}
		
		// Checkbox
		driver.findElement(By.className("gc-menu-icon")).click();

		// Select all
		List<WebElement> menuitems=driver.findElements(By.className("goog-menuitem"));
		for (WebElement menuitem:menuitems) {
		    if (menuitem.getText().equals("Select all")) {
			menuitem.click();
		    }
		}		
		
		// Delete forever
		driver.findElement(By.id("gc-inbox-delete")).click();
	    }
	} catch (Exception e) {
	}

	// quit
	driver.quit();	
    }
}

Misha Koshelev misha 680 at gmail dot com


Sign in to add a comment
Hosted by Google Code