0% found this document useful (0 votes)
120 views

Selenium Tutorial Selenium

This document provides an overview of Selenium tutorials, including: 1. Selenium is an open-source test automation suite used for automating web applications across browsers and platforms. It supports automation using different programming languages. 2. The main components of Selenium include Selenium IDE, Selenium RC, Selenium WebDriver, and Selenium Grid. Selenium WebDriver directly calls browser APIs and is the most widely used. 3. The document then discusses launching browsers in Selenium WebDriver using different drivers for Firefox, Chrome, Internet Explorer, and Safari browsers. It also covers setting up the driver paths and launching the browsers.

Uploaded by

Sunil Sasi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views

Selenium Tutorial Selenium

This document provides an overview of Selenium tutorials, including: 1. Selenium is an open-source test automation suite used for automating web applications across browsers and platforms. It supports automation using different programming languages. 2. The main components of Selenium include Selenium IDE, Selenium RC, Selenium WebDriver, and Selenium Grid. Selenium WebDriver directly calls browser APIs and is the most widely used. 3. The document then discusses launching browsers in Selenium WebDriver using different drivers for Firefox, Chrome, Internet Explorer, and Safari browsers. It also covers setting up the driver paths and launching the browsers.

Uploaded by

Sunil Sasi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

SELENIUM TUTORIALS

Selenium Introduction
Hello friends! this is our first tutorial of the Selenium tutorial series. In this tutorial, we will study the
basics of the Selenium suite, its different components, features, advantages, and limitations.
Content
 What is Selenium?
 Components of Selenium Suite
 Advantages of Selenium
 Limitations of Selenium
 What is Selenium WebDriver?
 Conclusion

What is Selenium?
Selenium is a free and open-source test automation suite used for automating web-based applications.
It supports automation across different browsers, platforms, and programming languages.
Using Selenium, we can automate the functional tests and easily integrate them with Maven, Jenkins,
and other build automation and continuous integration tools.

Components of Selenium Suite


Selenium Suite comprises of the following four components-
1. Selenium IDE – Selenium IDE is a record and playback automation tool using which we
can automate the web applications. It comes in the form of a Chrome and Firefox
browser extension.
Since it works on the record and playback principle, so it is the first-choice automation
tool for people with no or limited programming language experience.

2. Selenium RC – Selenium Remote Control (RC) is officially deprecated by Selenium. It


used to inject the JavaScript code in the browser for automation and required an
additional server for running the automation scripts.
Apart from this, it had many limitations like – it was slow, it didn’t have a headless
browser like HtmlUnitDriver and before executing the test scripts the server was
required to be started.

3. Selenium WebDriver – By far the most important component of Selenium Suite. It


provides different drivers for different browsers and supports multiple programming
languages.
It is purely object-oriented and supports all the major browsers – Chrome, Firefox, IE,
Safari, etc and scripting can be done in most of the popular languages – Java, Python,
Ruby, etc.
4. Selenium Grid – Selenium Grid is also an important part of the Selenium Suite. It helps
in the distributed running of Selenium tests in parallel across multiple remote machines.
It has a hub and multiple nodes. The nodes run the Selenium instances on which the test
cases are executed. These nodes are connected to a central hub which acts as a server
and controls the whole test execution.

Advantages of Selenium
Let’s now see some of the advantages of Selenium-
1. Selenium is open source, there is no licensing cost for its usage.
2. Scripting can be done in most of the widely used programming languages like Java, C#,
Ruby, and Python.
3. It provides platform support for all the major operating systems – Windows, Linux, Mac
OS, and Solaris.
4. It supports most of the popular browsers like Chrome, Firefox, Edge, Internet Explorer,
Opera, and Safari.
5. The Selenium IDE component of the Selenium suite provides record and playback
features using which non-programmers can also write automation scripts.
6. Selenium Grid helps in parallel and distributed testing.

Limitations of Selenium
Some of the limitations of Selenium are-
1. Selenium does not provide desktop application automation support.
2. Web Services – REST or SOAP cannot be automated using Selenium.
3. Selenium WebDriver requires programming language requirements for script creation.
4. For performing common tasks required in automation like logging, reading-writing to
external files, we have to rely on external libraries.
Let’s check the Selenium WebDriver component in a little more detail now.

What is Selenium WebDriver?


Selenium Webdriver is one of the most widely used tools for automating web applications. It automates
the browsers by calling their native method directly unlike Selenium RC which injects javascript in
browsers for automation. Hence, Webdriver is much faster than Selenium RC.

Apart from this, Selenium WebDriver can also handle scenarios like alerts, pop-ups, ajax requests,
keyboard, and mouse actions easily.

Since Webdriver directly calls the methods of different browsers hence we have a separate driver for
each browser.

Conclusion
This completes our tutorial on Introduction to Selenium and its most important component Selenium
WebDriver.
Launching Browsers in Selenium
Content
 Understanding the browser launching command
 Launching Firefox Browser
 Launching Chrome Browser
 Launching Internet Explorer Browser
 Launching Safari Browser

Understanding the browser launching command


As we have studied in previous tutorials that Selenium WebDriver calls the native methods of the
different browsers to automate them. Hence, in Selenium we have different WebDrivers for different
browsers like – FirefoxDriver for Firefox browser, ChromeDriver for Google Chrome,
InternetExplorerDriver for Internet Explorer, etc. Now let’s take an example of launching a Firefox
browser and understand the command in detail-
WebDriver driver = new FirefoxDriver();

This is the java implementation of launching a browser in Selenium. Here, ‘WebDriver’ is an interface
and we are creating a reference variable ‘driver’ of type WebDriver, instantiated using ‘FireFoxDriver’
class.
For those who are not very proficient in Java, an interface is like a contract that classes implementing it
must follow. An interface contains a set of variables and methods without anybody(no implementation,
only method name, and signature). We cannot instantiate objects from interfaces. Hence, the below line
of code is incorrect and throws a compile-time error saying “Cannot instantiate the type WebDriver”.
WebDriver driver = new WebDriver();

For instantiation of driver objects, we need classes like FirefoxDriver or ChromeDriver which have
implemented the WebDriver interface. In other words, these driver classes have followed the contract
of WebDriver by implementing all the methods of the WebDriver interface. Thus making all the different
types of driver classes uniform, following the same protocol.
Please note that we can also create a reference variable of type FirefoxDriver like this-
FirefoxDriver driver = new FirefoxDriver();
But having a WebDriver reference object helps in multi-browser testing as the same driver object can be
used to assign to any of the desired browser-specific drivers.

Launching Chrome Browser


For running the Chrome browser in Selenium, we need to set the webdriver.chrome.driver system
property to point to a chrome driver executable file-
1. Download the latest ChromeDriver binary from Chromium.org download page and place
the executable on your local machine.
2. Set the webdriver.chrome.driver property to the chromeDriver.exe’s location as-
System.setProperty(“webdriver.chrome.driver”, “chromeDriver.exe path”);

Code snippet to launch the Chrome browser-


public class ChromeBrowserLaunchDemo {
public static void main(String[] args) {

//Creating a driver object referencing WebDriver interface


WebDriver driver;

//Setting the webdriver.chrome.driver property to its executable's location


System.setProperty("webdriver.chrome.driver", "/lib/chromeDriver/chromedriver.exe");

//Instantiating driver object


driver = new ChromeDriver();

//Using get() method to open a webpage


driver.get("https://artoftesting.com");

//Closing the browser


driver.quit();}}

Launching Internet Explorer Browser


Like ChromeDriver, InternetExplorer driver also requires setting up the “webdriver.ie.driver” property
with the location of IEDriverServer.exe. The IEDriverServer.exe can be downloaded from  here. Following
code, snippet can be used to launch IE browser-
public class IEBrowserLaunchDemo {
public static void main(String[] args) {

//Creating a driver object referencing WebDriver interface


WebDriver driver;

//Setting the webdriver.ie.driver property to its executable's location


System.setProperty("webdriver.ie.driver", "/lib/IEDriverServer/IEDriverServer.exe");

//Instantiating driver object


driver = new InternetExplorerDriver();

//Using get() method to open a webpage


driver.get("https://artoftesting.com");

//Closing the browser


driver.quit();
}}

Launching Safari Browser


The Safari browser doesn’t require any additional configuration and can be directly launched by
instantiating with SafariDriver. The following code snippet can be used to launch the Safari browser-
public class SafariBrowserLaunchDemo {
public static void main(String[] args) {

//Creating a driver object referencing WebDriver interface


WebDriver driver;

//Instantiating driver object with SafariDriver


driver = new SafariDriver();

//Using get() method to open a webpage


driver.get("https://artoftesting.com");

//Closing the browser


driver.quit();
}
}
Locator in Selenium Web Drive
Hello friends! continuing with our “Selenium Automation” series, in this post we will study the different
types of locators available in Selenium. Before studying the different locators, let’s first see the need for
locators in the automation process.
A simple automation process in Selenium can be presented as-
 Launching browser
 Opening the desired website to be automated
 Locating web elements like a textbox
 Performing operations on the located web elements like writing in the textbox
 Performing assertion like checking ‘Success’ message

Now, let’s see a sample code snippet implementing the above process. We will be studying each line of
code in the coming tutorials. For now, just consider it as a black-box and focus on the operations
performed(specified in the comments).
//Launching Firefox browser
WebDriver driver = new FirefoxDriver();
//Opening google.com
driver.get("http://www.google.com");
//Initializing webelement searchBox
WebElement searchBox = driver.findElement(By.name("q"));
//Writing a text "ArtOfTesting" in the search box
searchBox.sendKeys("ArtOfTesting");
So, here we see that in order to perform an operation on web element – searchBox, we first need to
locate it. Here, By.name(“q”) is a locator which when passed to findElement method returns a
searchBox web element.

Before going further with the different types of locators available in Selenium, let’s first see, how to get
the different attributes of an element that are used in the locators.
Content
 Using Developer Tool
 Locators in Selenium

Using Developer Tool


Locating web elements requires knowledge of their HTML attributes. For the HTML source code of
specific elements, we can use the inbuilt developer tool (launched by pressing f12 in a browser).
Steps for finding element’s HTML attributes-
 Launch the website to be automated e.g. – https://www.google.com
 Press F12 to launch the developer tool.
 Click on the inspect-element icon as displayed in the image below.
 After clicking on the inspect-element icon, click on the web element to be located e.g.
Google Search box. Once we click on the element, its HTML will get displayed in the
firebug UI. 
 Here, we can see the different attributes of the web elements like – id, class, name,
along with its tag like input, div, etc. Now, we will be using these tags, attributes, and
values to locate elements using different locators.
Locators in Selenium
There are a total of 8 locators in Selenium WebDriver-
1. By Id – Locates element using id attribute of the web element.
WebElement element = driver.findElement(By.id("elementId"));
2. By className – Locates the web element using className attribute.
WebElement element = driver.findElement(By.className("objectClass"));
3. By tagName – Locates the web element using its HTML tag like div, a, input etc.
WebElement element = driver.findElement(By.tagName("a"));
4. By name – Locates the web element using name attribute.
WebElement element = driver.findElement(By.name("male"));
5. By linkText – Locates the web element of link type using their text.
WebElement element = driver.findElement(By.linkText("Click Here"));
6. By partialLinkText – Locates the web element of link type with partial matching of text.
WebElement element = driver.findElement(By.partialLinkText("Click"));
7. By cssSelector – Locates the web element using css its CSS Selector patterns(explained in detailed
here – CSS Locators).
WebElement element = driver.findElement(By.cssSelector("div#id"));
8. By xpath – Locates the web element using its XPaths(explained in detailed here XPath Locators).
WebElement element = driver.findElement(By.xpath("//div[@id='id']"));
Selenium WebDriver basic Commands
In this post, we will learn some of the basic selenium commands for performing operations like opening
a URL, clicking on buttons, writing in the textbox, closing the browser, etc. For your practice, a dummy
webpage with different types of web elements is available. Now, let’s see the basic commands of
Selenium WebDriver.
Content
 Opening a URL
 Using Get method-
 Using Navigate method-
 Clicking on WebElements
 Writing in a Textbox
 Clearing text in a Textbox
 Fetching text written over any web element
 Navigating backward in a browser
 Navigating forward in a browser
 Refreshing the browser
 Closing browser
 Sample Script

Opening a URL
Using Get method-
The driver.get() method is used to navigate to a web page by passing the string URL as parameter.
Syntax-
driver.get("https://artoftesting.com");

Using Navigate method-


The driver.navigate().to() method does the task of opening a web page like driver.get() method. Syntax-
driver.navigate().to("https://artoftesting.com");

Clicking on WebElements
The click() method in Selenium is used to perform the click operation on web elements. In our previous
tutorial, Locators in Selenium WebDriver, we studied about locating the webElements in Selenium. The
click() method is applied on the webElements identified, to perform the click operation.

//Clicking an element directly


driver.findElement(By.id("button1")).click();
//Or by first creating a WebElement and then applying click() operation
WebElement submitButton = driver.findElement(By.id("button2"));
submitButton.click();

Writing in a Textbox
The sendKeys() method can be used for writing in a textbox or any element of text input type.
//Creating a textbox webElement
WebElement element = driver.findElement(By.name("q"));
//Using sendKeys to write in the textbox
element.sendKeys("ArtOfTesting!");

Clearing text in a Textbox


The clear() method can be used to clear the text written in a textbox or any web element of text input
type.
//Clearing the text written in text fields
driver.findElement(By.name("q")).clear();

Fetching text written over any web element


In automation, many times we need to fetch the text written over a web element for performing some
assertions or debugging. For this, we have getText() method in selenium webDriver.
//Fetching the text written over web elements
driver.findElement(By.id("element123")).getText();

Navigating backward in a browser


Selenium provides navigate().back() command to move backward in the browser’s history.
//Navigating backwards in browser
driver.navigate().back();

Navigating forward in a browser


Selenium provides navigate().forward() command to move forward in a browser.
//Navigating forward in browser
driver.navigate().forward();

Refreshing the browser


There are multiple ways to refresh a page in Selenium WebDriver-
 Using driver.navigate().refresh() command
 Using sendKeys(Keys.F5) on any textbox on the webpage
 Using driver.get(“URL”) with current URL
 Using driver.navigate().to(“URL”) with current URL
//Refreshing browser using navigate().refresh()
driver.navigate().refresh();
//By pressing F5 key on any textbox element
driver.findElement(By.id("id123")).sendKeys(Keys.F5);
//By opening the current URL using get() method
driver.get("https://artoftesting.com");
//By opening the current URL using navigate() method
driver.navigate().to("https://artoftesting.com");

Closing browser
Selenium provides two commands to close browsers close() and quit(). The driver.close() command is
used to close the browser having focus. Whereas, the driver.quite() command is used to close all the
browser instances open.
//To close the current browser instance
driver.close();
//To close all the open browser instances
driver.quit();

Sample Script
You can use the sample script below to automate the dummy webpage. The comments mentioned
throughout the script will guide you through the whole automation process. Also, note that the
Thread.sleep() used in the sample script is to pause the automation in between events. This
Thread.sleep() is not required and is only included to provide you some time to see the automation
events.
Download this java file here – seleniumBasicCommands.java.
package myTestPackage;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import org.testng.annotations.Test;
public class seleniumBasicCommands {

public static void main(String Args[]) throws InterruptedException{

//Set system property for driver executable's path


System.setProperty("webdriver.gecko.driver", "{path to the browser driver}");

//Create Firefox driver's instance


WebDriver driver = new FirefoxDriver();

//Set implicit wait of 10 seconds


//This is required for managing waits in selenium webdriver
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//Launch sampleSiteForSelenium
driver.get("https://artoftesting.com/sampleSiteForSelenium");

//Fetch the text "This is sample text!" and print it on the console
//Use the id of the div to locate it and then fecth text using the getText() method
String sampleText = driver.findElement(By.id("idOfDiv")).getText();
System.out.println(sampleText);

//Waiting for 3 seconds just for the user to efficiently check automation
//Its not mandatory though
Thread.sleep(3000);

//Using linkText locator to find the link and then using click() to click on it
driver.findElement(By.linkText("This is a link")).click();

Thread.sleep(3000);

//Finding textbox using id locator and then using send keys to write in it
driver.findElement(By.id("fname")).sendKeys("Kuldeep Rana");

Thread.sleep(3000);

//Clear the text written in the textbox


driver.findElement(By.id("fname")).clear();

Thread.sleep(3000);

//Clicking on button using click() command


driver.findElement(By.id("idOfButton")).click();

Thread.sleep(3000);

//Find radio button by name and check it using click() function


driver.findElement(By.name("male")).click();

Thread.sleep(3000);

//Find checkbox by cssSelector and check it using click() function


driver.findElement(By.cssSelector("input.Automation")).click();
Thread.sleep(3000);

//Using Select class for for selecting value from dropdown


Select dropdown = new Select(driver.findElement(By.id("testingDropdown")));
dropdown.selectByVisibleText("Database Testing");

Thread.sleep(50000);

//Close the browser


driver.close();
}

}
Implicit & Explicit Waits in Selenium
Content
 Why are waits required in Selenium?
 Implicit Waits
 Explicit Waits
Why are waits required in Selenium?
In UI automation, waits are required because certain elements get loaded on the page asynchronously,
so after triggering an event a page may get loaded successfully but some of its elements may still not get
loaded.

This causes elementNotFound exception while locating the element. In such cases, we are left with
using Thread.sleep() i.e. a static wait that will halt the test execution for some specified time and then
perform the next step.
As Thread.sleep() will wait for the specified time no matter if the elements get visible before that time.
So, using Thread.sleep() is never advisable in UI automation.
To avoid this Selenium provides different types of waits, out of which Implicit and Explicit waits are most
commonly used.

Implicit Waits
An implicit wait when used is set to the WebDriver instance and is applied to all the web elements. In
implicit wait the webdriver polls the DOM to check the availability of the webElement and waits till the
maximum time specified before throwing NoSuchElementException.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

In the above code snippet, the value 20 specified in the implicit wait method is the maximum time in
seconds till which WebDriver will wait before throwing NoSuchElementException while locating a
WebElement.

Explicit Waits
Unlike implicit waits, the explicit waits are applied to each and every web element. In explicit wait,
certain conditions are defined for which the WebDriver instance waits before locating web elements or
performing actions on them. Some of the most common conditions specified in explicit waits are-
elementToBeClickable, presenceOfElementLocated etc.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.presenceOfElementLocated(ElementLocator));

You might also like