You are on page 1of 13

Advanced usage of Selenium WebDriver

27/08/2014
British Airways PLC

Sripriya Srinivasan (537208)


Airline Domain/Web Applications Automation
sripriya.vasan@tcs.com

Confidentiality Statement
Include the confidentiality statement within the box provided. This has to be legally
approved
Confidentiality and Non-Disclosure Notice
The information contained in this document is confidential and proprietary to TATA
Consultancy Services. This information may not be disclosed, duplicated or used for any
other purposes. The information contained in this document may not be released in
whole or in part outside TCS for any purpose without the express written permission of
TATA Consultancy Services.

Tata Code of Conduct


We, in our dealings, are self-regulated by a Code of Conduct as enshrined in the Tata
Code of Conduct. We request your support in helping us adhere to the Code in letter and
spirit. We request that any violation or potential violation of the Code by any person be
promptly brought to the notice of the Local Ethics Counselor or the Principal Ethics
Counselor or the CEO of TCS. All communication received in this regard will be treated
and kept as confidential.

1.

2.

Table of Content
Introduction to Selenium .......................................................................................................................................... 4
1.1

Selenium IDE ..................................................................................................................................................... 5

1.2

Selenium RC ...................................................................................................................................................... 5

1.3

Selenium WebDriver ......................................................................................................................................... 6

1.4

Selenium Grid .................................................................................................................................................... 6

Selenium 2................................................................................................................................................................. 7
2.1

3.

WebDriver and the Selenium-Server ................................................................................................................ 7

WebDriver: Advanced Usage ................................................................................................................................... 8


3.1

WebDriver Wait Commands ............................................................................................................................. 8

3.1.1

WebDriver.manage().timeouts() ............................................................................................................... 9

3.1.2

Support.ui.................................................................................................................................................. 9

3.2

Finding Dynamic Web Elements ..................................................................................................................... 11

1.

Introduction to Selenium

Selenium is an open source technology for automating browser-based applications. Selenium provides a
record/playback tool for authoring tests without learning a test scripting language. Test cases is selenium can be
written in HTML or many other popular programming languages supported by selenium like Java, C#, Groovy, Perl,
PHP, Python, Ruby etc. The tests can then be run against most modern web browsers. Selenium deploys on
Windows, Linux, and Macintosh platforms.
Selenium is composed of multiple software tools, each catering to different testing needs of an organization. It has
four components.

Selenium Integrated Development Environment (IDE)

Selenium Remote Control (RC) or Selenium 1

Selenium WebDriver

Selenium Grid

Selenium RC and WebDriver are merged into a single framework to form Selenium 2.

1.1 Selenium IDE


Selenium Integrated Development Environment (IDE) is the simplest framework in the Selenium suite and is the
easiest one to learn. It is a Firefox plugin that can be installed as easily as with other plugins. However, because of
its simplicity, Selenium IDE should only be used as a prototyping tool. Selenium RC or WebDriver needs to be used
to create more advanced test cases.
PROS

Very easy to use and install.


No programming experience is required, though knowledge of HTML and DOM are needed.
Can export tests to formats usable in Selenium RC and WebDriver.
Has built-in help and test results reporting module.
Provides support for extensions.

CONS

Available only in Firefox.


Designed only to create prototypes of tests.
No support for iteration and conditional operations.
Test execution is slow compared to that of Selenium RC and WebDriver.

1.2 Selenium RC
Selenium RC was the flagship testing framework of the whole Selenium project for a long time. This is the first
automated web testing tool that allowed users to use a programming language they prefer. As of version 2.25.0,
RC can support the following programming languages: Java, C#, PHP, Python, Perl and Ruby.
PROS

Cross-browser and cross-platform.


Can perform looping and conditional operations.
Can support data-driven testing.
Has matured and complete API.
Can readily support new browsers.
Faster execution then IDE.

CONS

Installation is more complicated then IDE.


Must have programming knowledge.
Needs selenium RC Server to be running.
API contains redundant and confusing commands.
Browser interaction is less realistic.
Inconsistent results & Uses JavaScript.
Slower execution time than WebDriver.

1.3 Selenium WebDriver


The WebDriver proves itself to be better than both Selenium IDE and Selenium RC in many aspects. It implements
a more modern and stable approach in automating the browser's actions. WebDriver, unlike Selenium RC, does
not rely on JavaScript for automation. It controls the browser by directly communicating to ti. The supported
languages are the same as those in Selenium RC.
PROS

Simpler installation than Selenium RC.


Communicates directly to the browser.
Browser interaction is more realistic.
No need for a separate component such as the RC Server.
Faster execution time than IDE and RC.

CONS

Installation is more complicated than Selenium IDE.


Requires programming knowledge.
Cannot readily support new browsers.
Has no built-in mechanism for logging runtime messages and generating test results.

1.4 Selenium Grid


Selenium Grid is a tool used together with Selenium RC to run parallel tests across different machines and different
browsers all at the same time. Parallel execution means running multiple tests at once.
Features:

Enables simultaneous running of tests in multiple browsers and environments.

Saves time enormously.

Utilizes the hub-and-nodes concept. The hub acts as a central source of Selenium commands to each node
connected to it.

2.

Selenium 2

The primary new feature in Selenium 2.0 is the integration of the WebDriver API. WebDriver is designed to provide
a simpler, more concise programming interface in addition to addressing some limitations in the Selenium-RC API.
Selenium-WebDriver was developed to better support dynamic web pages where elements of a page may change
without the page itself being reloaded. WebDrivers goal is to supply a well-designed object-oriented API that
provides improved support for modern advanced web-app testing problems.

2.1 WebDriver and the Selenium-Server


Selenium-WebDriver makes direct calls to the browser using each browsers native support for automation. How
these direct calls are made, and the features they support depends on the browser you are using. The Selenium
Server may, or may not be needed, depending on the intent to use Selenium-WebDriver. If the browser and tests
will all run on the same machine, and the tests only use the WebDriver API, then there is no need to run the
Selenium-Server; WebDriver will run the browser directly.
There are some reasons though to use the Selenium-Server with Selenium-WebDriver.

You are using Selenium-Grid to distribute your tests over multiple machines or virtual machines (VMs).

You want to connect to a remote machine that has a particular browser version that is not on your current
machine.
You are not using the Java bindings (i.e. Python, C#, or Ruby) and would like to use HtmlUnit Driver.

3.

WebDriver: Advanced Usage

3.1 WebDriver Wait Commands


Waiting is having the automated task execution elapse a certain amount of time before continuing with the next
step. Listing out the different WebDriver Wait statements that can be useful for an effective scripting and can
avoid using the Thread.sleep() commands.
A mind map of the different WebDriver commands is given below:

3.1.1 WebDriver.manage().timeouts()
implicitWait
The implicitWait will tell the WebDriver to poll the DOM for a certain duration when trying to find the element, this
will be useful when certain elements on the webpage will not be available immediately and needs some time to
load. By default it will take the value to 0, for the life of the WebDriver object instance throughout the test script.
Syntax:
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
pageLoadTimeout
Sets the amount of time to wait for a page load to complete before throwing an error. If the timeout is negative,
page loads can be indefinite.
Syntax:
driver.manage().timeouts().pageLoadTimeout(100, SECONDS);
setScriptTimeout
Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error. If the
timeout is negative, then the script will be allowed to run indefinitely.
Syntax:
driver.manage().timeouts().setScriptTimeout(100,SECONDS);

3.1.2 Support.ui
FluentWait
Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency
with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of
exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
Syntax:
// Waiting 30 seconds for an element to be present on the page, checking for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
9

ExpectedConditions
Models a condition that might reasonably be expected to eventually evaluate to something that is neither null nor
false. Examples would include determining if a web page has loaded or that an element is visible.
Note that it is expected that ExpectedConditions are idempotent. They will be called in a loop by the
WebDriverWait and any modification of the state of the application under test may have unexpected side-effects.
Syntax:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(>someid>)));
WebDriverWait
WebDriverWait will be used as we used in the Expected conditions code snippet as above. There are some
convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in
combination with ExpectedCondition is one way this can be accomplished.
Syntax:
WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));
Sleeper
Sleeper is something same as the Thread.sleep() method, but this with an Abstraction around the Thread.sleep()
for better testability. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to
wait.

10

3.2 Finding Dynamic Web Elements


Selenium RC has provisions for using methods like iSElementPresent and waitForCondition/waitForPageToLoad to
deal with Ajax and page loading events. With WebDriver, pre-defined methods are unavailable. Hence, it presents
the opportunity as well as the challenge to tailor ones need.
There are four important things that should be handled here:

Setting implicityWait to 0 so that WebDriver does not implicitly wait.

Returning True when the element is found.

Catching the NoSuchElementException and returning False when we discover that the element is not
present instead of stopping the test with an exception.
Setting implicitlyWait back to 10 after the action is complete so that WebDriver will implicitly wait in
future.

Syntax:
isElementPresent(WebDriver driver,By by)
{
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
try
{
driver.findElement(by);
return true;
}
catch(Exception e)
{
return false;
}
finally
{
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
}

11

Thus the presence of a web elements can be found out by passing the parameter in the below format:
boolean s = isElementPresent(driver,By.id("myDynamicElement"));
Either True or False is returned by the API.

12

Thank You

Contact
For more information, contact gsl.cdsfiodg@tcs.com (Email Id of ISU)
About Tata Consultancy Services (TCS)
Tata Consultancy Services is an IT services, consulting and business solutions
organization that delivers real results to global business, ensuring a level of certainty no
other firm can match. TCS offers a consulting-led, integrated portfolio of IT and ITenabled infrastructure, engineering and assurance services. This is delivered through its
TM
unique Global Network Delivery Model , recognized as the benchmark of excellence in
software development. A part of the Tata Group, Indias largest industrial conglomerate,
TCS has a global footprint and is listed on the National Stock Exchange and Bombay
Stock Exchange in India.
For more information, visit us at www.tcs.com.

IT Services
Business Solutions
Consulting
All content / information present here is the exclusive property of Tata Consultancy Services Limited (TCS). The content /
information contained here is correct at the time of publishing. No material from here may be copied, modified, reproduced,
republished, uploaded, transmitted, posted or distributed in any form without prior written permission from TCS.
Unauthorized use of the content / information appearing here may violate copyright, trademark and other applicable laws,
and could result in criminal or civil penalties. Copyright 2011 Tata Consultancy Services Limited