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.

114 Comments on “Implementation of Our First WebDriver Script – Selenium WebDriver Tutorial #10

  1. Exception in thread “main” java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases
    at com.google.common.base.Preconditions.checkState(Preconditions.java:754)
    at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
    at org.openqa.selenium.firefox.GeckoDriverService.access$100(GeckoDriverService.java:41)
    at org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:115)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:329)
    at org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:207)
    at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:103)
    at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:99)
    at pak0310.class0310.main(class0310.java:22)

    I got these error.

  2. Jennifer and subhash,

    Add these lines to the code

    System.setProperty(“webdriver.gecko.driver”, “”);

    It should work

  3. sorry it should be
    System.setProperty(“webdriver.gecko.driver”, “Path of gecko driver”);

  4. Very worthy guide to have with us.
    Very helpful to understand minutely.
    Can be ignored few codes with actual value for locating an element, might be because of change in requirement with webpage!!!
    Great effort, thanks a lot!!!

  5. As firefox always holds compatible issue, ppl can check chrome-it works fine with Se webdriver.
    Friends can try chrome browser if possible, but needs to install chrome driver in advance to local machine.

  6. Hi any one can help me about,when we are going to use locators(id,name,tag name..) while writing the scripts

  7. Please guide
    Getting below error while running the code:-
    Exception in thread “main” java.lang.NoClassDefFoundError: com/google/common/collect/ImmutableMap
    at org.openqa.selenium.remote.service.DriverService$Builder.(DriverService.java:249)
    at org.openqa.selenium.firefox.GeckoDriverService$Builder.(GeckoDriverService.java:115)
    at org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:164)
    at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:125)
    at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:103)
    at gmail_login.main(gmail_login.java:17)
    Caused by: java.lang.ClassNotFoundException: com.google.common.collect.ImmutableMap
    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)
    … 6 more

  8. Hi,
    very compliment for the intresting article!
    I’ve used WebDriver on a Win10 with Chrome browser, and now I’d like to manage a browser on Android.
    So I’m working with Android Studio, but I’m not able to start Chrome on Android.
    I’ve to install some package on Android?
    Many thanks

  9. Hi, I have this code and most of it seems to work but after I test the second next button it says incorrect password try again. Has the password changed? I am using this on Internet Explorer as this did not work on Firefox or Chrome drivers the first couple tries haha.

    Thanks in advance if you can tell me about the change in password

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.ie.InternetExplorerDriver;
    import org.openqa.selenium.remote.CapabilityType;
    import org.openqa.selenium.remote.DesiredCapabilities;

    public class Gmail_Login
    {
    /**
    * @param args
    *
    * @throws InterruptedException
    */
    public static void main(String[]args) throws
    InterruptedException {

    // objects and variables instantiation
    System.setProperty(“webdriver.chrome.driver”,”C:\\Users\\rdevu\\Documents\\selenium\\selenium\\chromedriver.exe”);
    System.setProperty(“webdriver.ie.driver”,”C:\\Users\\rdevu\\Documents\\selenium\\selenium\\IEDriverServer.exe”);
    DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
    capabilities.setCapability(CapabilityType.BROWSER_NAME, “IE”);
    capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);

    //it is used to initialize the IE driver
    WebDriver driver = new InternetExplorerDriver(capabilities);
    //WebDriver driver = new ChromeDriver();

    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();
    System.out.println(” “);

    // 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(“identifierId”));
    username.clear();
    username.sendKeys(“TestSelenium”);

    //click on next button
    WebElement nxtbtn = driver.findElement(By.id(“identifierNext”));
    nxtbtn.click();
    Thread.sleep(1000);

    // enter a valid password in the password textbox
    WebElement password = driver.findElement(By.name(“password”));
    password.clear();
    password.sendKeys(“password123”);

    WebElement nextbtn = driver.findElement(By.id(“passwordNext”));
    nextbtn.click();
    Thread.sleep(1000);

    // 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);
    }
    }

  10. Hi,

    I have gone as far as getting to the second next button only for them to tell me the password is incorrect using the following code:

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.ie.InternetExplorerDriver;
    import org.openqa.selenium.remote.CapabilityType;
    import org.openqa.selenium.remote.DesiredCapabilities;

    public class Gmail_Login
    {
    /**
    * @param args
    *
    * @throws InterruptedException
    */
    public static void main(String[]args) throws
    InterruptedException {

    // objects and variables instantiation
    System.setProperty(“webdriver.chrome.driver”,”C:\\Users\\rdevu\\Documents\\selenium\\selenium\\chromedriver.exe”);
    System.setProperty(“webdriver.ie.driver”,”C:\\Users\\rdevu\\Documents\\selenium\\selenium\\IEDriverServer.exe”);
    DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
    capabilities.setCapability(CapabilityType.BROWSER_NAME, “IE”);
    capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);

    //it is used to initialize the IE driver
    WebDriver driver = new InternetExplorerDriver(capabilities);
    //WebDriver driver = new ChromeDriver();

    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();
    System.out.println(” “);

    // 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(“identifierId”));
    username.clear();
    username.sendKeys(“TestSelenium”);

    //click on next button
    WebElement nxtbtn = driver.findElement(By.id(“identifierNext”));
    nxtbtn.click();
    Thread.sleep(1000);

    // enter a valid password in the password textbox
    WebElement password = driver.findElement(By.name(“password”));
    password.clear();
    password.sendKeys(“password123”);

    WebElement nextbtn = driver.findElement(By.id(“passwordNext”));
    nextbtn.click();
    Thread.sleep(1000);

    // 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);
    }
    }

    I have used an IE driver as it seemed to work better than Firefox or Chrome, can anyone please tell me if the password is changed and if so, what to?

    Thanks

  11. THE INFORMATION PROVIDED HERE IS VERY DETAILED AND CLEAR. BUT THIS IS WITH JAVA. CAN WE HAVE INFORMATION AND TUTORIALS ON SELENIUM WEB DRIVER SUPPORT IN PYTHON?

    • Yes, we will be publishing the Python guide soon. Stay tuned!

  12. hi,

    I’m using chrome driver for above programme.i’m getting error in password field.

    Exception in thread “main” org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {“method”:”id”,”selector”:”Passwd”}

  13. Hi,

    I am trying to locate one webElement for clickable button having same classname in the entire source.
    Code snippet below :

    button1 :
    Buy For Rs.2,845

    button 2 :
    Not Available

    How to manage the click on button 1.

    Please help.

Leave a Comment