DEV Community

Jessica Schuller
Jessica Schuller

Posted on

Write the First Script in Selenium Webdriver: Java code example

In this blog, you will be given an opportunity to get used to Selenium automation testing as well as the complete instructions of how to write a script in Selenium WebDriver as a basic level. The tutorial also provides you an actual Java code as a Selenium WebDriver example.

Audience

The tutorial provides automation testers the basic knowledge of how to write the script in Selenium Webdriver and practical examples. The article contains enough ingredients to let you start with Selenium WebDriver from where you can independently take yourself to higher levels of expertise.

Prerequisites

Before starting with this tutorial, you need to have a basic knowledge of Java or any other object-oriented coding language. Moreover, you should be proficient in the basic principles of testing concepts, especially the concept of Selenium Automation Testing.

Getting started with Selenium WebDriver Scripting

Assume that you want to write the script in Selenium Webdriver that could:

  • Fetch Fox News’ homepage
  • Verify its title
  • Print out the result of the comparison
  • Close it before ending the entire program

WebDriver code

Below is the Selenium WebDriver example for the logic presented by the scenario mentioned above.

Note: Gecko driver generated by Mozilla should be taken into account when using WebDriver. Selenium 3.0, Firefox and gecko have compatibility issues and setting them appropriately could become a difficult task. If the code cannot be activated, the lower version of Firefox should be downloaded. Otherwise, you can run your Selenium script on Chrome. You only need to change 3 lines of the code to let your script work with Firefox or Chrome.

package newproject;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

//comment the above line and uncomment below line to use Chrome

//import org.openqa.selenium.chrome.ChromeDriver;

public class PG1 {

public static void main(String[] args) {

// declaration and instantiation of objects/variables

System.setProperty("webdriver.firefox.marionette","C:\\geckodriver.exe");

WebDriver driver = new FirefoxDriver();

//comment the above 2 lines and uncomment below 2 lines to use Chrome

//System.setProperty("webdriver.chrome.driver","G:\\chromedriver.exe");

//WebDriver driver = new ChromeDriver();

String baseUrl = "http://www.foxnews.com/";

String expectedTitle = "Fox News - Breaking News Updates | Latest News Headlines | Photos & News Videos";

String actualTitle = "";

// launch Fire fox and direct it to the Base URL

driver.get(baseUrl);

// get the actual value of the title

actualTitle = driver.getTitle();

/*

* compare the actual title of the page with the expected one and print

* the result as "Passed" or "Failed"

*/

if (actualTitle.contentEquals(expectedTitle)){

System.out.println("Test Passed!");

} else {

System.out.println("Test Failed");

}

//close Fire fox

driver.close();

}

}

Explanation of the code

Importing Packages/Statements

First of all, you need to import the following two packages to be ready:

  1. org.openqa.selenium.*: references the WebDriver interface required to instantiate a new web browser.
  2. org.openqa.selenium.firefox.FirefoxDriver: references the FirefoxDriver class required to instantiate a Firefox-specific driver on the browser operated by the WebDriver class.

If your test requires more complex tasks such as capturing browser screens, accessing another class or manipulating external files, you definitely will need to import more packages.

Instantiating objects and variables

Generally, this is how a driver object is instantiated:

WebDriver driver - new FirefoxDriver();

The Base URL and the expected title are saved as variables.

Launching a Browser Session

WebDriver get() method helps launch a new browser session and deliver it directly to the URL that you specify as its parameter.

driver.get(baseUrl);

Getting the actual page title

You can verify the page title of the currently loading page by using the getTitle() method of the WebDriver interface.

actualTitle = driver.getTitle();

Comparing the Actual and Expected Values

This part of the code simply applies a basic Java if-else format to make a comparison between the actual and expected title.

 if (actualTitle.contentEquals(expectedTitle)){
System.out.println("Test Passed!");

} else {

System.out.println("Test Failed");

}

Ending a browser session

The close() method helps you to close the browser window.

  driver.close();

Ending the entire program

In case you use this command without closing all browser windows first, your entire Java program will be ended while the browser window is still opening.

system.exist(0)

Executing the test

There are two ways to run the code in Eclipse.

  1. On Eclipse menu bar, choose Run > Run.
  2. Press Ctrl+F11 to run the entire code.

Run on Eclipse Menu Bar

If you completed everything correctly, Eclipse would output “Test Passed!”

Test Passed

Locating Web Elements

We use the Dynamic finders findElement(By.locator()) to locate elements in WebDriver.

Following is an example code which locates an element by its id. Let’s take Facebook as an example of the Base URL.

package newproject;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

public class PG2 {

   public static void main(String[] args) {

    System.setProperty("webdriver.firefox.marionette","C:\\geckodriver.exe");

    WebDriver driver = new FirefoxDriver();

       String baseUrl = "http://www.facebook.com";

       String tagName = "";

       

       driver.get(baseUrl);

       tagName = driver.findElement(By.id("email")).getTagName();

       System.out.println(tagName);

       driver.close();

       System.exit(0);

}

}

We can use the getTagName() method to extract the tag name of the particular element whose id named “email”. When being executed, this code should have the ability to identify exactly the tag name “input” and will extract to Eclipse Console window.

Console

Locator Types and their Syntax

Locate by value of the “id” attributeLocate by value of the “class” attributeLocate by value of thetext of the hyperlinkLocate by value of thesub-text of the hyperlinkLocate by value of the“name” attributeLocate by value of the xpathLocate by value ofthe CSS selector

Locator Type Syntax Description
id driver.findElement (By.id(“ID_of_Element”)) Locate by value of the “id” attribute
className driver.findElement (By.className (“Class_of_Element”)) Locate by value of the “class” attribute
linkText driver.findElement (By.linkText(“Text”)) Locate by value of the text of the hyperlink
partialLinkText driver.findElement (By.partialLinkText (“PartialText”)) Locate by value of the sub-text of the hyperlink
name driver.findElement (By.name (“Name_of_Element”)) Locate by value of the “name” attribute
xpath driver.findElement (By.xpath(“Xpath”)) Locate by value of the xpath
cssSelector driver.findElement (By.cssSelector (“CSS Selector”)) Locate by value of the CSS selector
tagName driver.findElement (By.tagName(“input”)) Locate by value of its tag name

Conclusion

This tutorial provided you the instructions of how to write script in Selenium WebDriver in a basic level. The blog also discussed the different elements that constitute a Selenium WebDriver script.

Below is the summary of this Selenium WebDriver tutorial:

  • Before scripting, you need to import the packages which allow you to create a WebDriver script.
  • The get() method helps launch a pure web browser instance.
  • The getTitle() method retrieves the page title and assigns the retrieved title to a String object.
  • In WebDriver, we can locate web elements using Dynamic finders.
  • The following are the available locator types:
    • Id
    • className
    • name
    • XPath
    • cssSelector
    • linkText
    • partialLinkText
    • tagName

Top comments (0)