Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Write Your First Script in Selenium WebDriver

DZone 's Guide to

How to Write Your First Script in Selenium WebDriver

Learn more about using Java and Selenium WebDriver for test automation.

· Java Zone ·
Free Resource

In this blog, you will be given an opportunity to get used to Selenium automation testing as well as the basic instructions on how to write a script in Selenium WebDriver with sample Java code to get you started.

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 three 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();

}

}


Code Explanation

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.

The following is an example code that 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  is 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

Locator Type Syntax Description
id

driver.findElement

(By.id(“ID_of_Element”))

Locate by the value of

the “id” attribute

className

driver.findElement

(By.className

(“Class_of_Element”))

Locate by the value of

the “class” attribute

linkText

driver.findElement

(By.linkText(“Text”))

Locate by the value of the

text of the hyperlink

partialLinkText

driver.findElement

(By.partialLinkText

(“PartialText”))

Locate by the value of the

sub-text of the hyperlink

name

driver.findElement

(By.name

(“Name_of_Element”))

Locate by the value of the

“name” attribute

xpath

driver.findElement

(By.xpath(“Xpath”))

Locate by the value

of the xpath

cssSelector

driver.findElement

(By.cssSelector

(“CSS Selector”))

Locate by the value of

the CSS selector

tagName

driver.findElement

(By.tagName(“input”))

Locate by the value of

its tag name

Conclusion

This tutorial provided you instructions on how to write a script in Selenium WebDriver. 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
Topics:
selenium testing tutorial ,selenium web driver ,java ,automation ,test automation ,tutorial ,java testing tutorial ,webdriver

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}