Selenium 2.0 WebDriver – its easy to learn!!

by seetaram on June 4, 2011

I wanted to evaluate Selenium 2.0 hence went through the Selenium 2.0 and WebDriver documentation and tried writing some simple tests with JUnit.4  Its really easy to understand.  Lot of changes, its like entirely a new tool.

APIs are pretty straight forward and easy to use.  Let us have a look at the following code.

package com.selftechy.webdriver;

import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SearchGoogle {
protected static WebDriver driver;	

	public static void setUp() throws Exception {
        driver = new FirefoxDriver();

	public void testGoogleSearch() throws Exception {

	public static void tearDown() throws Exception {


To write the above code, I have not used Selenium IDE but used Firebug. / Firepath  Using Firebug we can find out ID, name, xpath, etc of an object. If you know little bit of HTML DOM (should know what is ID, name, tag, xpath, etc) then using the APIs such as findElement, it is very easy to automate test cases.

The above code searches for “selftechy” in Google and then opens up the website by clicking on the search result.  It uses API – findElement and methods – click, get, submit, sendkeys, etc.

Since WebDriver provides an option to find out elements using link text / partial link text, it is easy to click on the link as well as locate them on the application.

One more thing I want to mention here is with WebDriver, there is no need to run Selenium RC for standalone tests.  Just go to Run As and click on JUnit Test., it starts executing the test.

If you ask me to choose between Selenium 1.x & Selenium 2.0 WebDriver, I would suggest the latter.

{ 30 comments… read them below or add one }

rajat June 16, 2011 at 6:09 am

hi ,
i have troubled you with so many doubts , but hopefully this is the last one . what i did after adding all the required libraries , i just executed the code that you have pasted above and executed it as a JUNIT test case , it threw a very big error , ihave pasted the stack trace here to help you get to the root of the problem , i am a fresher adn i am trying my best , please help me by giving me ideas . thankyou so much .

org.openqa.selenium.NoSuchElementException: Unable to locate element: {“method”:”partial link text”,”selector”:””}
For documentation on this error, please visit:
System info: ‘Linux’, os.arch: ‘amd64’, os.version: ‘2.6.35-28-generic’, java.version: ‘1.6.0_24’
Driver info: driver.version: RemoteWebDriver
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(
at java.lang.reflect.Constructor.newInstance(
at org.openqa.selenium.remote.ErrorHandler.createThrowable(
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(
at org.openqa.selenium.remote.RemoteWebDriver.execute(
at org.openqa.selenium.remote.RemoteWebDriver.findElement(
at org.openqa.selenium.remote.RemoteWebDriver.findElementByPartialLinkText(
at org.openqa.selenium.By$ByPartialLinkText.findElement(
at org.openqa.selenium.remote.RemoteWebDriver.findElement(
at com.SearchGoogle.testGoogleSearch(
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(
at sun.reflect.DelegatingMethodAccessorImpl.invoke(
at java.lang.reflect.Method.invoke(
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(
at org.junit.runners.model.FrameworkMethod.invokeExplosively(
at org.junit.internal.runners.statements.InvokeMethod.evaluate(
at org.junit.runners.BlockJUnit4ClassRunner.runChild(
at org.junit.runners.BlockJUnit4ClassRunner.runChild(
at org.junit.runners.ParentRunner$
at org.junit.runners.ParentRunner$1.schedule(
at org.junit.runners.ParentRunner.runChildren(
at org.junit.runners.ParentRunner.access$000(
at org.junit.runners.ParentRunner$2.evaluate(
at org.junit.internal.runners.statements.RunBefores.evaluate(
at org.junit.internal.runners.statements.RunAfters.evaluate(
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(
Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: Unable to locate element: {“method”:”partial link text”,”selector”:””}
System info: ‘Linux’, os.arch: ‘amd64’, os.version: ‘2.6.35-28-generic’, java.version: ‘1.6.0_24’
Driver info: driver.version: unknown
at .WebDriverError(file:///tmp/anonymous658283804924060749webdriver-profile/extensions/
at .(file:///tmp/anonymous658283804924060749webdriver-profile/extensions/ -> file:///tmp/anonymous658283804924060749webdriver-profile/extensions/
at .(file:///tmp/anonymous658283804924060749webdriver-profile/extensions/ -> file:///tmp/anonymous658283804924060749webdriver-profile/extensions/
at .(file:///tmp/anonymous658283804924060749webdriver-profile/extensions/
at .(file:///tmp/anonymous658283804924060749webdriver-profile/extensions/
at .(file:///tmp/anonymous658283804924060749webdriver-profile/extensions/
at .(file:///tmp/anonymous658283804924060749webdriver-profile/extensions/


seetaram June 19, 2011 at 7:37 am

Hey Rajat,

I was little busy and could not log in to see the comments.. Let me answer your questions… please feel free to mail me at


seetaram June 19, 2011 at 7:46 am

@ Rajat,

“org.openqa.selenium.NoSuchElementException: Unable to locate element: ”

Above error will be thrown when Selenium is unable to locate the element on the application. For example, you are trying to look up for an URL which should have displayed on the browser if the previous step was successfully executed but for some reason, it is not displayed and the Selenium is throwing the above error.

If you are using Eclipse, then use Debug mode (Step In/ Step out – F10 / F11) and try to debug it step by step then you can get to the root of the error. Try to put “wait” as much as possible because Selenium might be executing faster than the application. Also, you can slow down the execution speed of the Selenium with setSpeed(value) – value should be in milliseconds.

I hope this will solve your problem. Please feel free to send me questions on


bhoomika July 12, 2011 at 6:59 pm

Hi Seetaram,

I am total new to selenium and am trying to write a script using webdriver to send mail fro gmail. I am getting error “Unable to locate element: {“method”:”xpath”,”selector”:”/html/body/div[1]/div[2]/div/div[2]/div[1]/div[1]/div[1]/div[3]/div[@id=’:k5′]/div[1]/div[@id=’:k6′]/div/div”}”

I am guessing that for some reason the page is not loading properly because of which the xpath is not being resolved. Could you please help me with this.
Please see the code below:

package com.selenium.scripts;

import junit.framework.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class gmail {
static WebDriver driver;
static Wait wait;
private static final String USER_NAME = “”;
private static final String PASSWORD = “”;
private static final String EMAIL = “”;
private static final String SUBJECT = “Subject & Body only mail”;
private static final String MAIL_BODY = “Hi, How r u doing”;

public static void main(String[] args) {
driver = new FirefoxDriver();
wait = new WebDriverWait(driver, 100);
boolean result;
try {
result = Signin();
} catch(Exception e) {
result = false;
} finally {
System.out.println(“Test ” + (result? “passed.” : “failed.”));
if (!result) {

private static boolean Signin() {
//type search query
// click search
// Wait for search to complete


wait.until(new ExpectedCondition() {
public Boolean apply(WebDriver webDriver) {
System.out.println(“Signing-in …”);
return Boolean.valueOf(true);


if(driver.getPageSource().contains(“Compose mail”)) { System.out.println(“Successful login to Gmail”); }

//Clicking on Compose mail button

//Entering the destination email address in “To” field

//Entering the subject in “Subject” field

//Entering email content
driver.findElement(By.xpath(“//html/body[@class=’editable LW-yrriRe’]”)).sendKeys(MAIL_BODY);

//Sending the email by clicking on Send button

//Look for message confirming that the message has been sent.
return driver.findElement(By.tagName(“body”)).getText().contains(“Your message has been sent”);



bhoomika July 12, 2011 at 7:01 pm

Adding the my environment details:
Windows 7, Firefox4. Selenium 2, jdk1.6.0_25 and eclipse IDE


seetaram July 13, 2011 at 6:00 pm

Hi Bhoomika,

the problem is with your “xpath”. On the same page, open Selenium IDE, copy and paste the “/html/body/div[1]/div[2]/div/div[2]/div[1]/div[1]/div[1]/div[3]/div[@id=’:k5′]/div[1]/div[@id=’:k6′]/div/div” in target field and then click Find button. If it highlights the element then only Selenium is going to identify, otherwise the test will fail. Please refer my post on “writing xpath” and try to understand xpath that will definitely help you


Sarthak August 5, 2011 at 10:09 am


I am very new to selenium. I started with selenium 2.0. If my understanding is correct, webdriver can be run without starting selenium server. But i always get connection refused error. However it works fine when i start the server. Is there any solution for this.

com.thoughtworks.selenium.SeleniumException: Connection refused: connect

My testcode:

public void login_FF() throws Exception {

FirefoxDriver driver = new FirefoxDriver();

/* new WebDriverWait(driver, 15).until(new

new WebDriverWait(driver, 60).until(new
new WebDriverWait(driver, 15).until(new
ElementPresent(By.linkText(“Sign up / Login”)));
driver.findElement(By.linkText(“Sign up / Login”)).click();

new WebDriverWait(driver, 20).until(new

new WebDriverWait(driver, 15).until(new

new WebDriverWait(driver, 15).until(new

WebElement body = driver.findElement(By.tagName(“body”));
//System.out.println(body.getText().contains(“Activation Complete!”));

// if(tagID.getText().contains(“Activation Complete!!”)) {
// System.out.println(“Exists!”);



seetaram August 6, 2011 at 4:51 am

Try to add Standalone Server JAR file to the build path


seetaram August 18, 2011 at 7:51 am

Use the following Webdriver APIs to handle NoSuchElementException:



joneric wennerstrom January 30, 2012 at 9:31 pm

Selenium 2.0 is anything but easy. It is incredibly difficult and complex to use on anything but the simplest of websites. The ridiculously simple example given at the top is completely misleading. Try working with frames, javascript generated menu’s, popup windows, javascript generated trees, then tell me that it’s easy. You must be a developer in order to use it. Selenium 1.0 and the IDE was easy to use and non-developers could write test cases and test suites with minimal help from developers. Those days are completely gone forever. You must be an experienced web developer in order to use Selenium 2.0.


seetaram February 4, 2012 at 3:08 am

Hello Joneric,

Even with Selenium 1.0, if you have 1000+ test cases, tell me is it possible to record and run using Selenium IDE? I would say NO!! Again you must know JAVA (at least core Java) to handle such number of TCs. If you have that expertise, then even the WebDriver is also easy as explained in the example.

Nothing is easy in this world unless we know the job very well. Selenium IDE is bit improving in order to support WebDriver (Selenium 2.0) but still there are lot more to go.



Ashwini March 13, 2012 at 10:08 am

i am new to selenium webdriver, i want to write a code to send email by providing the data(usernamr and password) from excel sheet. Please help me how to write a code for this task .


seetaram March 24, 2012 at 9:28 am

I have already written some articles on WebDriver.. look into it.. that will definitely be useful for beginners…


ranjithkukam December 5, 2012 at 11:59 am

package com.Google;

import java.util.concurrent.TimeUnit;

import jxl.Sheet;
import jxl.Workbook;

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

public class DataDrivenTestingMultiple {

public static void main(String args[]) throws Exception{
DataDrivenTestingMultiple d= new DataDrivenTestingMultiple();

public void testDatadrivenJUnit() throws Exception
FileInputStream fi=new FileInputStream(“C:\\Users\\User three\\Desktop\\Selenium\\ranjith1.xls”);
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(“ranjith”);
for (int i = 0; i <= s.getColumns(); i++)

for(int j = 0; j < s.getRows() ;j++)
WebDriver driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(10000, TimeUnit.SECONDS);
driver.get( "; );
WebElement e = driver.findElement("q"));
System.out.println("Searched for the term "+s.getCell(i,j).getContents());




catch(Exception e)



jignesh April 17, 2012 at 6:00 am

Hello, sitaram,
can you please tell me how to check if element is present or not on the page using webdriver.
i just want to check if radio button is available or not. but in web driver there is no such method like iselementpresent.

so let me know how to find out this.



pavan March 25, 2013 at 1:35 pm

public String isElementPresent(String xpathkey)
System.out.println(“Element is present”);

}catch(Exception t)

return “fail – element is not present ” + xpathkey;
return “pass”;


jignesh April 17, 2012 at 6:40 am


Here is another concern.. how to verify and enter vlaue in window pop up.. i have window pop up. and have to insert uname and password,., its not javascript.. so how to hadle this??. switchto window is not working for same..


martin April 17, 2012 at 11:15 pm

Ashwini, if all you want to do is send email you don’t need selenium, just use javamail-1.4.4. There are tons of samples out there.


Vikas Singh July 9, 2012 at 11:02 am

Hi i am new to Webdrvier. I have to automate an application using framework. But i dont know what approach would be best. So for now what i have done is:
1. I created a object repository in Excel sheet.

ObjectName Selector Locator
Search xpath //input[@id=search]

2. Then i created a class which contains keywords. I created a simple keyword ‘Click’. In which enter the object name which u need to be clicked. This keyword will pick up the object from excel and perform the action. Keyword code is:
Code to Pickup the object from Excel:

public static String[] GetObject(String Object) throws BiffException, IOException{

int x=0;
int y=0;
int column2 = 0;
File inputWorkbook = new File(inputFile);
Workbook workbook;

workbook = Workbook.getWorkbook(inputWorkbook);
Sheet sheet = workbook.getSheet(0);
for (int j = 0; j < sheet.getColumns(); j++) {
for (int i = 0; i < sheet.getRows(); i++) {
Cell cell = sheet.getCell(j, i);
CellType type = cell.getType();
String value=cell.getContents();
if (value.equals(Object)){
Cell cell1=sheet.getCell(x, y);
String value=cell1.getContents();
Cell cell11=sheet.getCell(x, y);
String value2=cell11.getContents();
String ob[]=new String[2];
String temp = value;
if(value.equalsIgnoreCase("Object Name") && value2.equalsIgnoreCase("Selector")){
System.out.println("Object not Found");
for (int i=0; i<2; i++){


return ob;

public static void Click(String ObjectName) throws BiffException, IOException{
String Selector=object[0];
String locator=object[1];
else if(object[0].equalsIgnoreCase("xpath"))
else if(object[0].equalsIgnoreCase("name"))
else if(object[0].equalsIgnoreCase("linkText"))
else if(Selector.equalsIgnoreCase("cssSelector"))

3. After this i created another class in which i created a flow of application.

Can anyone tell me that am i following correct approach or not????


Syed January 10, 2013 at 5:21 pm

Hi Seetaram,

I am new to setting up Selenium server in Nagios running on Linux box. I went through many Selenium documents eg:-,-Forms-and-Transactions/check_selenium/details.

1) I wanted to set up synthetic transaction monitors using Selenium Webdriver. I was able to use configure the Selenium IDE on firefox and record the testcase. in my windows box. Later I exported to java file (File -> Export Test Case As … -> Java (JUnit4) – Webdriver).

2) I can open the testcase(not the java file) in firefox and run it fine.

3) Now I want to compile the Java file in the Linux box.

4) I am not able to compile the java file in linux box “javac -cp junit-4.8.1.jar:selenium-server.jar”. I get errors :- cannot find symbol
symbol : method timeouts()
location: interface org.openqa.selenium.WebDriver.Options
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
^ cannot find symbol
symbol : method alert()
location: interface org.openqa.selenium.WebDriver.TargetLocator
Alert alert = driver.switchTo().alert();
2 errors

5) The blog says that there is no need for Selenium RC server to run at the backend.

6) Can you please help me in step by step procedure to configure the webdriver in linux box, compile the java file to class file and execute the test in linux box?

I referred most of the selenium blogs but not able to get it right. Can you please help me.

Thanks in advance.



Chethana September 13, 2013 at 6:32 am

Hi I am new to Selenium Webdriver.Can you please suggest me the best framework to use with (TestNg or Junit).and if it is TestNG which is best
TestNg with Maven OR TestNG with Ant?


seetaram September 16, 2013 at 4:39 am

TestNG is better, Maven and Ant are almost same. Maven is better.


ritu December 8, 2013 at 1:15 am

When trying to findelement by tagname(“title”) on Yahoo site it gives timeout error, even if the timeout is set to 120 seconds. But when i try to find element by id it works fine. Can you please tell me what could be the reason?


seetaram January 10, 2014 at 7:04 am

“title” you are trying to access might be wrong


Isabella May 25, 2016 at 9:12 am

It’s a joy to find somenoe who can think like that


yujin September 1, 2014 at 9:47 am

When try to selectFrame by xpath(“//iframe[contains(@src,’theme/mrc/jsp/crm/sitemap.jsp’)]”) it gives error.
the error infomation is follow:
Caused by: org.openqa.selenium.NoSuchFrameException: Unable to locate frame
Can you please tell me what could be the reason?

html as follow:


Dheeraj November 20, 2014 at 4:42 am


I am facing issue with accessing gmail URL using webdriver. Gmail URL is unreachable on server but its working fine on local.

Can you please let us know which exactly settings required to access gmail URL ?


Veronika May 23, 2015 at 6:02 pm

Pretty! This was an incredibly wonderful article.
Thanks for providing this info.


reklama lubin odrodzenia August 9, 2015 at 9:19 pm

Hi, yeah this article is genuinely nice and I have learned lot of things from it
regarding blogging. thanks.


USA Proxies June 5, 2016 at 6:19 am

Good respond in return of this query with solid arguments
aand telling everything on the topic of that.


Leave a Comment

Previous post:

Next post:

Do you want to get updates on the recent articles written? Please subscribe to RSS feed or Email