Write the First Script in Selenium Webdriver: Java code example
Tags: seleniumtutorials, seleniumwebdriver
Published: 2018-11-28 08:39:32

---
title: Write the First Script in Selenium Webdriver: Java code example
published: true
description: This article provides the complete instructions of how to write a script in Selenium WebDriver and an actual Java code as a Selenium WebDriver example.
tags: Selenium Tutorials, Selenium Webdriver
---
<p style="text-align: left;">In this blog, you will be given an opportunity to get used to Selenium automation testing as well as the complete instructions of <strong>how to write a script in Selenium WebDriver</strong> as a basic level. The tutorial also provides you an actual Java code as a <strong>Selenium WebDriver example</strong>.</p>

<h2>Audience</h2>
The tutorial provides automation testers the basic knowledge of <strong>how to write the script in Selenium Webdriver</strong> 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.
<h2>Prerequisites</h2>
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 <strong>Selenium Automation Testing</strong>.
<h2>Getting started with Selenium WebDriver Scripting</h2>
Assume that you want to <strong>write the script in Selenium Webdriver</strong> that could:
<ul>
 	<li>Fetch Fox News’ homepage</li>
 	<li>Verify its title</li>
 	<li>Print out the result of the comparison</li>
 	<li>Close it before ending the entire program</li>
</ul>
<h2>WebDriver code</h2>
Below is the <a href="https://seleniumtestingtutorials.com/selenium-webdriver/write-script-sel…m-webdriver-java/" target="_blank" rel="noopener"><strong>Selenium WebDriver example</strong></a> 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.
<pre class="">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 &amp; 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();

}

}</pre>
<h2>Explanation of the code</h2>
<h3>Importing Packages/Statements</h3>
First of all, you need to import the following two packages to be ready:
<ol>
 	<li><strong>org.openqa.selenium.*: </strong>references the WebDriver interface required to instantiate a new web browser.</li>
 	<li><strong>org.openqa.selenium.firefox.FirefoxDriver</strong>: references the FirefoxDriver class required to instantiate a Firefox-specific driver on the browser operated by the WebDriver class.</li>
</ol>
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.
<h3>Instantiating objects and variables</h3>
Generally, this is how a driver object is instantiated:
<pre class="">WebDriver driver - new FirefoxDriver();</pre>
The Base URL and the expected title are saved as variables.
<h3>Launching a Browser Session</h3>
WebDriver <strong>get() </strong>method helps launch a new browser session and deliver it directly to the URL that you specify as its parameter.
<pre>driver.get(baseUrl);</pre>
<h3>Getting the actual page title</h3>
You can verify the page title of the currently loading page by using the <strong>getTitle()</strong> method of the WebDriver interface.
<pre>actualTitle = driver.getTitle();</pre>
<h3>Comparing the Actual and Expected Values</h3>
This part of the code simply applies a basic Java if-else format to make a comparison between the actual and expected title.
<pre class="lang:default decode:true"> if (actualTitle.contentEquals(expectedTitle)){
System.out.println("Test Passed!");

} else {

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

}</pre>
<h3>Ending a browser session</h3>
The <strong>close()</strong> method helps you to close the browser window.
<pre>  driver.close();</pre>
<h3>Ending the entire program</h3>
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.
<pre class="">system.exist(0)</pre>
<h2>Executing the test</h2>
There are two ways to run the code in Eclipse.
<ol>
 	<li>On Eclipse menu bar, choose <strong>Run</strong> &gt; <strong>Run</strong>.</li>
 	<li>Press <strong>Ctrl+F11</strong> to run the entire code.</li>
</ol>
<figure class="wp-block-image"><img class="aligncenter wp-image-365 size-full" src="https://seleniumtestingtutorials.com/wp-content/uploads/2018/10/Selenium-WebDriver-1-1.png" alt="Run on Eclipse Menu Bar" width="369" height="99" /></figure>
If you completed everything correctly, Eclipse would output “Test Passed!”
<figure class="wp-block-image"><img class="size-full wp-image-366 aligncenter" src="https://seleniumtestingtutorials.com/wp-content/uploads/2018/10/Selenium-WebDriver-2-1.png" alt="Test Passed" width="177" height="115" /></figure>
<h2>Locating Web Elements</h2>
We use the Dynamic finders <strong>findElement(By.locator())</strong> 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.
<table>
<tbody>
<tr>
<td>
<pre>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);

}

}</pre>
</td>
</tr>
</tbody>
</table>
We can use the <strong>getTagName() </strong>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.
<figure class="wp-block-image"><img class="size-full wp-image-367 aligncenter" src="https://seleniumtestingtutorials.com/wp-content/uploads/2018/10/Selenium-WebDriver-3-1.png" alt="Console" width="176" height="112" /></figure>
<h2>Locator Types and their Syntax</h2>
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
<table class="wp-block-table">
<tbody>
<tr>
<td>Locator Type</td>
<td>Syntax</td>
<td>Description</td>
</tr>
<tr>
<td>id</td>
<td>driver.findElement(By.id(“ID_of_Element”))</td>
</tr>
<tr>
<td>className</td>
<td>driver.findElement(By.className(“Class_of_Element”))</td>
</tr>
<tr>
<td>linkText</td>
<td>driver.findElement(By.linkText(“Text”))</td>
</tr>
<tr>
<td>partialLinkText</td>
<td>driver.findElement(By.partialLinkText(“PartialText”))</td>
</tr>
<tr>
<td>name</td>
<td>driver.findElement(By.name(“Name_of_Element”))</td>
</tr>
<tr>
<td>xpath</td>
<td>driver.findElement(By.xpath(“Xpath”))</td>
</tr>
<tr>
<td>cssSelector</td>
<td>driver.findElement(By.cssSelector(“CSS Selector”))</td>
</tr>
<tr>
<td>tagName</td>
<td>driver.findElement(By.tagName(“input”))</td>
<td>Locate by value ofits tag name</td>
</tr>
</tbody>
</table>
<h2>Conclusion</h2>
This tutorial provided you the instructions of <a href="https://seleniumtestingtutorials.com/selenium-webdriver/write-script-sel…m-webdriver-java/" target="_blank" rel="noopener"><strong>how to write script in Selenium WebDriver </strong></a> 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:
<ul>
 	<li>Before scripting, you need to import the packages which allow you to create a WebDriver script.</li>
 	<li>The <strong>get()</strong> method helps launch a pure web browser instance.</li>
 	<li>The <strong>getTitle()</strong> method retrieves the page title and assigns the retrieved title to a String object.</li>
 	<li>In WebDriver, we can locate web elements using Dynamic finders.</li>
 	<li>The following are the available locator types:
<ul>
 	<li>Id</li>
 	<li>className</li>
 	<li>name</li>
 	<li>XPath</li>
 	<li>cssSelector</li>
 	<li>linkText</li>
 	<li>partialLinkText</li>
 	<li>tagName</li>
</ul>
</li>
</ul>