Selenium 2.0 WebDriver – its easy to learn!!

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;	

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

	@Test
	public void testGoogleSearch() throws Exception {
		driver.get("http://www.google.com");
		driver.findElement(By.name("q")).sendKeys("selftechy");
		driver.findElement(By.name("q")).submit();
		driver.findElement(By.name("btnG")).click();
		driver.findElement(By.partialLinkText("Selftechy.com")).click();
	}

	@AfterClass
	public static void tearDown() throws Exception {
		driver.quit();
	}
}

 

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 www.selftechy.com 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.

Comments 30

  • 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”:”Selftechy.com”}
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
    System info: os.name: ‘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(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:131)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:105)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:409)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:192)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByPartialLinkText(RemoteWebDriver.java:225)
    at org.openqa.selenium.By$ByPartialLinkText.findElement(By.java:246)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:184)
    at com.SearchGoogle.testGoogleSearch(SearchGoogle.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
    Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: Unable to locate element: {“method”:”partial link text”,”selector”:”Selftechy.com”}
    System info: os.name: ‘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/fxdriver@googlecode.com/resource/modules/utils.js:7420)
    at .(file:///tmp/anonymous658283804924060749webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js -> file:///tmp/anonymous658283804924060749webdriver-profile/extensions/fxdriver@googlecode.com/components/firefoxDriver.js:469)
    at .(file:///tmp/anonymous658283804924060749webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js -> file:///tmp/anonymous658283804924060749webdriver-profile/extensions/fxdriver@googlecode.com/components/firefoxDriver.js:492)
    at .(file:///tmp/anonymous658283804924060749webdriver-profile/extensions/fxdriver@googlecode.com/resource/modules/utils.js:266)
    at .(file:///tmp/anonymous658283804924060749webdriver-profile/extensions/fxdriver@googlecode.com/components/nsCommandProcessor.js:306)
    at .(file:///tmp/anonymous658283804924060749webdriver-profile/extensions/fxdriver@googlecode.com/components/nsCommandProcessor.js:320)
    at .(file:///tmp/anonymous658283804924060749webdriver-profile/extensions/fxdriver@googlecode.com/components/nsCommandProcessor.js:197)

    • 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 selftechy@gmail.com

    • @ 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 selftechy@gmail.com

  • 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;
    import org.openqa.selenium.support.ui.ExpectedCondition;
    import org.openqa.selenium.support.ui.Wait;
    import org.openqa.selenium.support.ui.WebDriverWait;

    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);
    driver.get(“https://www.google.com/accounts/ServiceLogin?service=mail&passive=true&rm=false&continue=http%3A%2F%2Fmail.google.com%2Fmail%2F%3Fui%3Dhtml%26zy%3Dl&bsv=llya694le36z&scc=1&ltmpl=default&ltmplcache=2&from=login”);
    boolean result;
    try {
    result = Signin();
    } catch(Exception e) {
    e.printStackTrace();
    result = false;
    } finally {
    driver.close();
    }
    System.out.println(“Test ” + (result? “passed.” : “failed.”));
    if (!result) {
    System.exit(1);
    }

    }
    private static boolean Signin() {
    //type search query
    driver.findElement(By.name(“Email”)).sendKeys(USER_NAME);
    // click search
    driver.findElement(By.name(“Passwd”)).sendKeys(PASSWORD);
    // Wait for search to complete
    //driver.findElement(By.name(“signIn”)).click();
    driver.findElement(By.name(“signIn”)).click();

    //Assert.assertTrue(driver.getPageSource().contains(“Inbox”));

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

    }
    });

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

    //Clicking on Compose mail button
    driver.findElement(By.xpath(“/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”)).click();

    //Entering the destination email address in “To” field
    driver.findElement(By.name(“to”)).sendKeys(EMAIL);

    //Entering the subject in “Subject” field
    driver.findElement(By.name(“subject”)).sendKeys(SUBJECT);

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

    //Sending the email by clicking on Send button
    driver.findElement(By.xpath(“//div[@role=’button’]/b”)).click();

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

    }

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

    • 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

  • Hi,

    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:

    @Test
    public void login_FF() throws Exception {

    FirefoxDriver driver = new FirefoxDriver();
    driver.get(“https://www.lebara-mobile.co.uk”);

    /* new WebDriverWait(driver, 15).until(new
    ElementPresent(By.id(“cmp_action_link_top1”)));
    driver.findElement(By.id(“cmp_action_link_top1”)).click();

    new WebDriverWait(driver, 60).until(new
    ElementPresent(By.id(“login”)));
    System.out.println(“login!!”);
    System.out.println(driver.findElement(By.id(“login”)));
    System.out.println(driver.findElement(By.tagName(“iframe”)));
    driver.switchTo().frame(driver.findElement(By.tagName(“iframe”)));
    */
    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
    ElementPresent(By.id(“loginID”)));
    driver.findElement(By.id(“loginID”)).sendKeys(“leb002@gmx.com”);

    new WebDriverWait(driver, 15).until(new
    ElementPresent(By.id(“loginID”)));
    driver.findElement(By.id(“password”)).sendKeys(“lebara123”);

    new WebDriverWait(driver, 15).until(new
    ElementPresent(By.xpath(“//form[@id=’login’]/button”)));
    driver.findElement(By.xpath(“//form[@id=’login’]/button”)).click();

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

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

    }

  • Try to add Standalone Server JAR file to the build path

  • Use the following Webdriver APIs to handle NoSuchElementException:

    driver.manage().setSpeed(Speed.SLOW);
    Thread.sleep(1000);

  • 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.

    • 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.

      Regards,
      Seetaram

  • Hi,
    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 .

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

    • package com.Google;

      import java.io.FileInputStream;
      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();
      d.testDatadrivenJUnit();
      }

      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”);
      System.out.println(s.getRows());
      System.out.println(“haiiiii”);
      System.out.println(s.getColumns());
      try{
      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( "http://www.google.com&quot; );
      WebElement e = driver.findElement(By.name("q"));
      e.sendKeys(s.getCell(i,j).getContents());
      System.out.println("Searched for the term "+s.getCell(i,j).getContents());
      e.submit();

      Thread.sleep(1000);
      driver.quit();

      }

      }

      }
      catch(Exception e)
      {
      e.getMessage();
      }
      }

      }

  • 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.

    Thanks
    Jignesh

    • public String isElementPresent(String xpathkey)
      {
      System.out.println(“Element is present”);
      try{
      driver.findElement(By.xpath(OR.getProperty(xpathkey)));

      }catch(Exception t)
      {

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

  • Hello,,

    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..

  • 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.

  • 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)){
    x=j+1;
    column2=j+2;
    y=i;
    break;
    }
    }
    }
    Cell cell1=sheet.getCell(x, y);
    String value=cell1.getContents();
    x=x+1;
    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");
    }
    else{
    for (int i=0; i<2; i++){

    ob[i]=temp;
    temp=value2;
    }

    }
    return ob;
    }

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

    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????

  • Hi Seetaram,

    I am new to setting up Selenium server in Nagios running on Linux box. I went through many Selenium documents eg:- http://exchange.nagios.org/directory/Plugins/Websites,-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 xxxxxx.java”. I get errors :-
    Webmail02TestCaseWebDriver.java:22: cannot find symbol
    symbol : method timeouts()
    location: interface org.openqa.selenium.WebDriver.Options
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    ^
    Webmail02TestCaseWebDriver.java:60: 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.

    Regards,
    Syed.

  • 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?

  • 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?

  • 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:

  • Hi,

    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 ?

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

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.