Implementation of Our First WebDriver Script – Selenium WebDriver Tutorial #10

In the previous two tutorials, we made you acquainted with the basic architecture and features of WebDriver and the infrastructure required to get started with Selenium WebDriver. Assuming that you all might have set up the system with all the necessary utilities and packages, we will move further with the implementation of our first WebDriver test script.

Therefore, motioning ahead with the consequent Selenium WebDriver tutorial, we would be creating WebDriver script. We would also scatter the light on the basic and commonly used WebDriver commands. We would also learn about the locating strategies of UI elements and their inclusion in the test scripts. We would also study Get Commands in the detail.

Selenium WebDriver Tutorial

Script Creation

For script creation, we would be using “Learning_Selenium” project created in the previous tutorial and “gmail.com” as the application under test (AUT).

Scenario:

  • Launch the browser and open “Gmail.com”.
  • Verify the title of the page and print the verification result.
  • Enter the username and Password.
  • Click on the Sign in button.
  • Close the web browser.

Step 1: Create a new java class named as “Gmail_Login” under the “Learning_Selenium” project.

Step 2: Copy and paste the below code in the “Gmail_Login.java” class.

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

public class Gmail_Login {
/**
* @param args
*/
       public static void main(String[] args) {
             
// objects and variables instantiation
              WebDriver driver = new FirefoxDriver();
              String appUrl = "https://accounts.google.com";
             
// launch the firefox browser and open the application url
              driver.get(appUrl);
             
// maximize the browser window
              driver.manage().window().maximize();
             
// declare and initialize the variable to store the expected title of the webpage.
              String expectedTitle = " Sign in - Google Accounts ";
             
// fetch the title of the web page and save it into a string variable
              String actualTitle = driver.getTitle();
             
// compare the expected title of the page with the actual title of the page and print the result
              if (expectedTitle.equals(actualTitle))
              {
                     System.out.println("Verification Successful - The correct title is displayed on the web page.");
              }
             else
              {
                     System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
              }

// enter a valid username in the email textbox
              WebElement username = driver.findElement(By.id("Email"));
              username.clear();
              username.sendKeys("TestSelenium");
             
// enter a valid password in the password textbox
              WebElement password = driver.findElement(By.id("Passwd"));
              password.clear();
              password.sendKeys("password123");
             
// click on the Sign in button
              WebElement SignInButton = driver.findElement(By.id("signIn"));
              SignInButton.click();
             
// close the web browser
              driver.close();
              System.out.println("Test script executed successfully.");
             
// terminate the program
              System.exit(0);
       }
}

The above code is equivalent to the textual scenario presented earlier.

Code Walkthrough

Import Statements:

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

Prior to the actual scripting, we need to import the above packages:

import org.openqa.selenium.WebDriver – References the WebDriver interface which is required to instantiate a new web browser.

import org.openqa.selenium.firefox.FirefoxDriver – References the FirefoxDriver class that is required instantiate a Firefox specific driver on the browser instance instantiated using WebDriver interface.

import org.openqa.selenium.WebElement – References to the WebElement class which is required to instantiate a new web element.

import org.openqa.selenium.By – References to the By class on which a locator type is called.

As and when our project would grow, it is evident and logical that we might have to introduce several other packages for more complex and distinct functionalities like excel manipulations, database connectivity, logging, assertions etc.

Object Instantiation

WebDriver driver = new FirefoxDriver();

We create a reference variable for WebDriver interface and instantiate it using FirefoxDriver class. A default Firefox profile will be launched which means that no extensions and plugins would be loaded with the Firefox instance and that it runs in the safe mode.

Launching the Web browser

driver.get(appUrl);

A get() method is called on the WebDriver instance to launch a fresh web browser instance. The string character sequence passed as a parameter into the get() method redirects the launched web browser instance to the application URL.

Maximize Browser Window

driver.manage().window().maximize();

The maximize() method is used to maximize the browser window soon after it is re-directed to the application URL.

Fetch the page Title

driver.getTitle();

The getTitle() method is used to fetch the title of the current web page. Thus, the fetched title can be loaded to a string variable.

Comparison between Expected and Actual Values:

if (expectedTitle.equals(actualTitle))
              {
                     System.out.println("Verification Successful - The correct title is displayed on the web page.");
              }
              else
              {
                     System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
              }

The above code uses the conditional statement java constructs to compare the actual value and the expected value. Based on the result obtained, the print statement would be executed.

WebElement Instantiation

WebElement username = driver.findElement(By.id(“Email”));

In the above statement, we instantiate the WebElement reference with the help of “driver.findElement(By.id(“Email”))”. Thus, username can be used to reference the Email textbox on the user interface every time we want to perform some action on it.

Clear Command

username.clear();

The clear() method/command is used to clear the value present in the textbox if any. It also clears the default placeholder value.

sendKeys Command

username.sendKeys(“TestSelenium “);

The sendKeys() method/command is used to enter/type the specified value (within the parentheses ) in the textbox. Notice that the sendKeys() method is called on the WebElement object which was instantiated with the help of element property corresponding to the UI element.

The above block of code enters the string “TestSelenium” inside the Email textbox on the Gmail application.


sendKeys is one of the most popularly used commands across the WebDriver scripts.

Click Command

SignInButton.click();

Like sendKeys(), click() is another excessively used command to interact with the web elements. Click() command/method is used to click on the web element present on the web page.

The above block of code clicks on the “Sign in” button present on the Gmail application.

Notes:

  • Unlike sendKeys() method, click() methods can never be parameterized.
  • At times, clicking on a web element may load a new page altogether. Thus to sustain such cases, click() method is coded in a way to wait until the page is loaded.

Close the Web Browser

driver.close();

The close() is used to close the current browser window.

Terminate the Java Program

System.exit(0);

The Exit() method terminates the Java program forcefully. Thus, remember to close all the browser instances prior terminating the Java Program.

Test Execution

The test script or simply the java program can be executed in the following ways:

#1. Under the Eclipse’s menu bar, there is an icon to execute the test script. Refer the following figure.

WebDriver tutorial 1

Make a note that only the class which is selected would be executed.

#2. Right click anywhere inside the class within the editor, select “Run As” option and click on the “Java Application”.

#3. Another shortcut to execute the test script is – Press ctrl + F11.

At the end of the execution cycle, the print statement “Test script executed successfully.” can be found in the console.

Locating Web Elements

Web elements in WebDriver can be located and inspected in the same way as we did in the previous tutorials of Selenium IDE. Selenium IDE and Firebug can be used to inspect the web element on the GUI. It is highly suggested to use Selenium IDE to find the web elements. Once the web element is successfully found, copy and paste the target value within the WebDriver code. The types of locators and the locating strategies are pretty much the same except for the syntax and their application.

In WebDriver, web elements are located with the help of the dynamic finders (findElement(By.locatorType(“locator value”))).

Sample Code:

driver.findElement(By.id(“Email”));

WebDriver tutorial 2

Locator Types and their Syntax

Locator TypeSyntaxDescription
iddriver.findElement
(By.id(“ID_of_Element”))
Locate by value of
the “id” attribute
classNamedriver.findElement
(By.className
(“Class_of_Element”))
Locate by value of
the “class” attribute
linkTextdriver.findElement
(By.linkText(“Text”))
Locate by value of the
text of the hyperlink
partialLinkTextdriver.findElement
(By.partialLinkText
(“PartialText”))
Locate by value of the
sub-text of the hyperlink
namedriver.findElement
(By.name
(“Name_of_Element”))
Locate by value of the
“name” attribute
xpathdriver.findElement
(By.xpath(“Xpath”))
Locate by value
of the xpath
cssSelectordriver.findElement
(By.cssSelector
(“CSS Selector”))
Locate by value of
the CSS selector
tagNamedriver.findElement
(By.tagName(“input”))
Locate by value of
its tag name

Conclusion

In this tutorial, we developed an automation script using WebDriver and Java. We also discussed the various components that constitute a WebDriver script.

Here are the cruxes of this Selenium WebDriver Tutorial:

  • Prior to the actual scripting, we need to import a few packages to be able to create a WebDriver script.
    • importopenqa.selenium.By;
    • importopenqa.selenium.WebDriver;
    • importopenqa.selenium.WebElement;
    • importopenqa.selenium.firefox.FirefoxDriver;
  • A get() method used to launch a fresh web browser instance. The character sequence passed as a parameter into the get() method redirects the launched web browser instance to the application URL.
  • The maximize() method is used to maximize the browser window.
  • The clear() method is used to clear the value present in the textbox if any.
  • The sendKeys() method is used to enter the specified value in the textbox.
  • Click() method is used to click on the web element present on the web page.
  • In WebDriver, web elements can be located using Dynamic finders.
  • The following are the available locator types:
    • id
    • className
    • name
    • xpath
    • cssSelector
    • linkText
    • partialLinkText
    • tagName

Moving ahead, in the next tutorial, we would shift our focus towards a framework that aids to Automation testing known as TestNG. We would have a detailed study on the various kinds of the annotations provided by the framework.

Next tutorial #11: Before diving deep into Frameworks we will see details about JUnit – an open source unit testing tool. Most of the programmers use JUnit as it is easy and does not take much effort to test. This tutorial will give an insight about JUnit and its usage in selenium script.

A remark for the readers: While our next tutorial of the Selenium series is in the processing mode, readers can start creating their own basic WebDriver scripts. For more advance scripts and concepts, we will have various other Selenium WebDriver tutorials coming up in this series.

Let us know in comments if you have any problem creating or executing the WebDriver scripts.

Recommended Reading


115 thoughts on “Implementation of Our First WebDriver Script – Selenium WebDriver Tutorial #10”

  1. Nice one…
    I have a query:
    I want to test the web application through webdriver which is created on .net technology.
    Which programming language should I use for webdriver so that it will ease to identify web application elements?

    Hope you got the question, please provide your valuable feedback on that.

    Thanks,
    Hitesh

  2. @Hitesh

    Thank you for your kind words.
    WebDriver is independent of the language you have written your application in.
    So you can use any programming language for WebDriver script creation but the best suited would be C#.

  3. thanks. this is a really helpful tutorial series.
    Could you please provide example test scripts using TestNG as well (comparing JUnit)?
    and Could you please describe the differences between JUnit and the TestNG scripts (keywords etc.)?

  4. Thanks for the nice article. The script is executed before the page loads, hence I am getting “Verification Failed …………………..”. if there any way, we can wait to load the web page completely before start locating the web elements or performing any action on it.

    Please suggest.

  5. @Papak

    There are several ways to wait fro the page to load.
    You can use explicit or Implicit waits.
    We have a tutorial coming up soon based on the same subject which would help you.

  6. @ Shruti,

    One correction needs to be done in dynamic class locator syntax- it should be as- driver.findElement(By.Class(” class name”))

  7. Hi Shruti,

    For example: I have written a code to automate yahoomail “https://login.yahoo.com/config/login_verify2?&.src=ym&.intl=us”, then it does not recognize the objects which we had identified using Firebug in default mode. How to handle this issue when we are running a script.

  8. Hi Shruti,

    After copy-pasting the code, I got the following msg in the console:

    Error: Main method not found in class Gmail_Login, please define the main method as:
    public static void main(String[] args)

    Could you help?

  9. Hi ..
    I have a query hence im new to the selenium environment.
    in the above secnario you said that verify the title and print the result. So, please tell me how to print the result. For that i am getting an error message verification failed. Plz reply me with the solution as soon as possible.

  10. Thanks for such a wonderful material..
    I Have some query
    I am set up webdriver and create script and also run script , but my query is its working in practical environment .. Suppose i am working on a login page .
    In that case how Automation work?
    Please help me Asap

  11. Thanks for such a wonderful material..
    I Have some query
    I am set up webdriver and create script and also run script , but my query how its working in practical environment .. Suppose i am working on a login page .
    In that case how Automation work?
    Please help me Asap

  12. Hi, Thank you for this wonderful tutorial. Pardon me for asking questions. I tried to follow through the steps and run my script in eclipse. However, I got this error which I am not sure what to do. I am not a technical person but would like to learn the automation. Is there a chance that you could take a look at my concern? Thank you.

    Here’s the error i got when I run it in eclipse:

    Exception in thread “main” org.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA
    Build info: version: ‘2.44.0’, revision: ’76d78cf’, time: ‘2014-10-23 20:03:00’
    System info: host: ‘WS-PH-DEG’, ip: ‘10.163.91.23’, os.name: ‘Windows 7’, os.arch: ‘amd64’, os.version: ‘6.1’, java.version: ‘1.8.0_25’
    Driver info: driver.version: FirefoxDriver
    at org.openqa.selenium.firefox.internal.Executable.(Executable.java:72)
    at org.openqa.selenium.firefox.FirefoxBinary.(FirefoxBinary.java:59)
    at org.openqa.selenium.firefox.FirefoxBinary.(FirefoxBinary.java:55)
    at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:95)
    at Gmail_Login.main(Gmail_Login.java:13)

  13. Need Help. I get an error when I run the following code:

    package invokeff;
    import java.util.List;

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    /**
    *
    * @author JayantDesktop
    */
    public class InvokeFF {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
    WebDriver driver = new FirefoxDriver();

    // TODO code application logic here
    }

    }

    Output —-
    run:
    Exception in thread “main” java.lang.NoClassDefFoundError: com/google/common/base/Function
    at invokeff.InvokeFF.main(InvokeFF.java:23)
    Caused by: java.lang.ClassNotFoundException: com.google.common.base.Function
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    … 1 more
    Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)

  14. i get the following error when i run

    Exception in thread “main” java.lang.NoClassDefFoundError: com/google/common/base/Function
    at com.gmail.GmailLogin2A.main(GmailLogin2A.java:13)
    Caused by: java.lang.ClassNotFoundException: com.google.common.base.Function
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    … 1 more

  15. Hi Shruti, The script is executing well but the browser is not getting closed but still displaying the message “Test script executed successfully.”. Can you please let me know why browser doesnt close and is there any alternative to close.

  16. Hi Raji, Lee
    I got the same your issue and I fixed it successfully. I bet you guys missed some jar files while adding to Java project.
    Steps:
    1. Download the Selenium Java Client Libraries at http://docs.seleniumhq.org/download/ (in previous tutorial)
    2. Right click on Java Project –>Properties–>Java Build Path–>Add External Jar
    3. Select all jar files in Lib folder (I only added two other files and ignored this folder before)
    4. Click Ok
    5. Refresh project and run again

    Hope helpful

  17. Hi,
    Thanks for the selenium tutorial series :) It’s much appreciated!

    I am trying to run the sample program given here, but I am also getting the same error as:
    Exception in thread “main” java.lang.NoClassDefFoundError: com/google/common/base/Function
    at Test001.main(Test001.java:20)

    The line that seems to be giving the error is :
    WebDriver driver = new FirefoxDriver();

    I have added both the Selenium jars to the java project, but even then I am getting the error and hence I am unable to execute my script.

    Any help would be much appreciated, tia!

  18. When i pasted the program in eclipse after importing all the libraries, i am getting the error “The method sendKeys(CharSequence[]) in the type WebElement is not applicable for the arguments (String)” in the line”username.sendKeys(“TestSelenium”);”

  19. When i pasted the program in eclipse after importing all the libraries, i am getting the error “The method sendKeys(CharSequence[]) in the type WebElement is not applicable for the arguments (String)” in the line”username.sendKeys(“TestSelenium”);”

  20. The script is executing well but the browser is not getting closed but still displaying the message “Test script executed successfully.”. Can you please let me know why browser doesnt close and is there any alternative to close.

  21. When i am running above program..i am receiving belwom mentioed error

    java.lang.NoClassDefFoundError: Gmail_Login
    Caused by: java.lang.ClassNotFoundException: Gmail_Login
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)

  22. Hi Shruti,

    While clicking on a hyperlink, a new window opens. When I try to automate any of the web elements in that new window, it is throwing NoSuchElementFoundException. I dont see any iframes as well.

    Please suggest.

  23. 5th of June 2015:

    As the login for accounts has changed for email (it requires pressing a button after entering the login name) the script should also be updated to reflect this. Have adjusted it myself to go to the second page using a Click, but in the second window it will not enter the password, even though the element naming is correct.

    I’m also wondering about starting Firefox in safe mode, can this be changed? When doing so it doesn’t pick up on my normal network settings, resulting in no pages being loaded. I now need to manually set it and go to the google account page before the script kicks off.

  24. we need to add delay, how we do that?
    the browser comesup and vanishes immeditely

    error is as follows
    Exception in thread “main” org.openqa.selenium.WebDriverException: unknown error: Chrome version must be >= 42.0.2311.0
    (Driver info: chromedriver=2.16.333243 (0bfa1d3575fc1044244f21ddb82bf870944ef961),platform=Windows NT 6.1 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 2.39 seconds
    Build info: version: ‘2.30.0’, revision: ‘dc1ef9ceb805a672f56dc49198f9ffbd4ca345c7’, time: ‘2013-02-19 09:14:38’
    System info: os.name: ‘Windows 7’, os.arch: ‘amd64’, os.version: ‘6.1’, java.version: ‘1.8.0_25’
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

  25. Hi Sruthi,

    When i run the above code in eclipse I am getting the below error.

    Exception in thread “main” java.lang.Error: Unresolved compilation problems:
    WebDriver cannot be resolved to a type
    FirefoxDriver cannot be resolved to a type
    WebElement cannot be resolved to a type
    By cannot be resolved
    WebElement cannot be resolved to a type
    By cannot be resolved
    WebElement cannot be resolved to a type
    By cannot be resolved

    at Gmail_Login.main(Gmail_Login.java:13)

    I am new to selinium and trying to learn self. Please help me where the issue is .

    Thank you

  26. Hi Shruti, If I am running a script which has sendkeys then I get an error “The type java.lang.CharSequence cannot be resolved. It is indirectly refernced from required .class files.Can u please help me with this.

  27. Hi Shruti,

    When I run it, I got the following error. Can you please let me know what needs to be done to fix it.

    Exception in thread “main” org.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: MAC
    Build info: version: ‘2.46.0’, revision: ’87c69e2′, time: ‘2015-06-04 16:17:10’
    System info: host: ‘Yadav’, ip: ‘192.168.0.102’, os.name: ‘Mac OS X’, os.arch: ‘x86_64’, os.version: ‘10.10.1’, java.version: ‘1.8.0_25’
    Driver info: driver.version: FirefoxDriver
    at org.openqa.selenium.firefox.internal.Executable.(Executable.java:74)
    at org.openqa.selenium.firefox.FirefoxBinary.(FirefoxBinary.java:60)
    at org.openqa.selenium.firefox.FirefoxBinary.(FirefoxBinary.java:56)
    at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:124)
    at Gmail_Login.main(Gmail_Login.java:20)

  28. Hi @Bharadwaj, @Jones Gold, @Kumar

    Please follow this steps for the error
    “The method sendKeys(CharSequence[]) in the type WebElement is not applicable for the arguments (String)” in the line”username.sendKeys(“TestSelenium”);”

    It has a simple solution. Change your compiler compliance level from 1.4 to 1.7.

    Follow these steps in your eclipse:

    Right click on your java project and select Build Path -> Click on
    Configure Build Path…
    In project properties window, Click/select Java Compiler at the left
    panel
    At the right panel, change the Compiler compliance level from 1.4 to 1.7
    (Select which is higher version in your eclipse)
    Lastly Click on Apply and OK
    Now check your code. it will never show the same error.

  29. Hi!
    Very helpful tutorial, just one quick question… I get this error message on every single import:
    “The import …. cannot be resolved”

    I’ve added all the libraries in the past tutorial, can you please tell me what am I missing and/or doing wrong?

  30. The account login has “Next ” element after the username.You need to locate this element ,and provide an implicit wait,before entering your username!

    Here is my code:

    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    // click next
    WebElement Next = driver.findElement(By.name(“signIn”));
    Next.click();

  31. Hi thanks for best Tutorial

    I have query

    At line 39 its displaying error driver can not be resolved

    please tell me HOW TO SOLVE THIS ISSUE

  32. Hi,

    Very good selenium tutorial content. Keep up the good work.

    Do we need to download Firefox Driver for Selenium as I am getting error while running this code “Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms.”?

    Thanks!

  33. @ Gene Dela Cruz

    Make sure that firefox must install on ->(c:/program files/mozilla firefox ) If firefox is install some other place than selenium show those error. If you want to use firefox on any other place than use set capabilities similar we have done in case with Chrome and other respective browsers

Leave a Comment