0% found this document useful (0 votes)
717 views173 pages

About Sellinum

This document provides an introduction and overview of Selenium, an open source test automation tool for web applications. It discusses the advantages of test automation and introduces the various tools within the Selenium suite, including Selenium WebDriver, Selenium RC, Selenium IDE, and Selenium Grid. A brief history is given of the Selenium project and how it merged with WebDriver to become the most widely used and fully-featured open source solution for automating web tests.

Uploaded by

webiis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
717 views173 pages

About Sellinum

This document provides an introduction and overview of Selenium, an open source test automation tool for web applications. It discusses the advantages of test automation and introduces the various tools within the Selenium suite, including Selenium WebDriver, Selenium RC, Selenium IDE, and Selenium Grid. A brief history is given of the Selenium project and how it merged with WebDriver to become the most widely used and fully-featured open source solution for automating web tests.

Uploaded by

webiis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 173

Table Of Contents

Introduction
Test Automation for Web Applications
To Automate or Not to Automate?
Introducing Selenium
Brief History of The Selenium Project
Seleniums Tool Suite
!hoosing "our Selenium Tool
Supported Bro#sers and Platforms
$le%ibility and &%tensibility
Whats in this Boo'?
The (ocumentation Team)Authors Past and Present
Introduction
Test Automation for Web Applications
*any+ perhaps most+ soft#are applications today are #ritten as #eb,based applications to be run in an Internet bro#ser- The effecti.eness of
testing these applications .aries #idely among companies and organi/ations- In an era of highly interacti.e and responsi.e soft#are
processes #here many organi/ations are using some form of Agile methodology+ test automation is fre0uently becoming a re0uirement for
soft#are projects- Test automation is often the ans#er- Test automation means using a soft#are tool to run repeatable tests against the
application to be tested- $or regression testing this pro.ides that responsi.eness-
There are many ad.antages to test automation- *ost are related to the repeatability of the tests and the speed at #hich the tests can be
e%ecuted- There are a number of commercial and open source tools a.ailable for assisting #ith the de.elopment of test automation- Selenium
is possibly the most #idely,used open source solution- This users guide #ill assist both ne# and e%perienced Selenium users in learning
effecti.e techni0ues in building test automation for #eb applications-
This users guide introduces Selenium+ teaches its features+ and presents commonly used best practices accumulated from the Selenium
community- *any e%amples are pro.ided- Also+ technical information on the internal structure of Selenium and recommended uses of
Selenium are pro.ided-
Test automation has specific ad.antages for impro.ing the long,term efficiency of a soft#are teams testing processes- Test automation
supports1
$re0uent regression testing
2apid feedbac' to de.elopers
3irtually unlimited iterations of test case e%ecution
Support for Agile and e%treme de.elopment methodologies
(isciplined documentation of test cases
!ustomi/ed defect reporting
$inding defects missed by manual testing
To Automate or Not to Automate?
Is automation al#ays ad.antageous? When should one decide to automate test cases?
It is not al#ays ad.antageous to automate test cases- There are times #hen manual testing may be more appropriate- $or instance+ if the
applications user interface #ill change considerably in the near future+ then any automation might need to be re#ritten any#ay- Also+
sometimes there simply is not enough time to build test automation- $or the short term+ manual testing may be more effecti.e- If an
application has a .ery tight deadline+ there is currently no test automation a.ailable+ and its imperati.e that the testing get done #ithin that
time frame+ then manual testing is the best solution-
Introducing Selenium
Selenium is a set of different soft#are tools each #ith a different approach to supporting test automation- *ost Selenium 4A &ngineers
focus on the one or t#o tools that most meet the needs of their project+ ho#e.er learning all the tools #ill gi.e you many different options
for approaching different test automation problems- The entire suite of tools results in a rich set of testing functions specifically geared to the
needs of testing of #eb applications of all types- These operations are highly fle%ible+ allo#ing many options for locating 5I elements and
comparing e%pected test results against actual application beha.ior- 6ne of Seleniums 'ey features is the support for e%ecuting ones tests
on multiple bro#ser platforms-
Brief History of The Selenium ro!ect
Selenium first came to life in 7889 #hen :ason Huggins #as testing an internal application at ThoughtWor's- Being a smart guy+ he reali/ed
there #ere better uses of his time than manually stepping through the same tests #ith e.ery change he made- He de.eloped a :a.ascript
library that could dri.e interactions #ith the page+ allo#ing him to automatically rerun tests against multiple bro#sers- That library
e.entually became Selenium !ore+ #hich underlies all the functionality of Selenium 2emote !ontrol ;2!< and Selenium I(&- Selenium 2!
#as ground,brea'ing because no other product allo#ed you to control a bro#ser from a language of your choice-
While Selenium #as a tremendous tool+ it #asnt #ithout its dra#bac's- Because of its :a.ascript based automation engine and the security
limitations bro#sers apply to :a.ascript+ different things became impossible to do- To ma'e things #orse+ #ebapps became more and more
po#erful o.er time+ using all sorts of special features ne# bro#sers pro.ide and ma'ing this restrictions more and more painful-
In 788= a pluc'y engineer at >oogle named Simon Ste#art started #or' on a project he called Web(ri.er- >oogle had long been a hea.y
user of Selenium+ but testers had to #or' around the limitations of the product- Simon #anted a testing tool that spo'e directly to the bro#ser
using the ?nati.e method for the bro#ser and operating system+ thus a.oiding the restrictions of a sandbo%ed :a.ascript en.ironment- The
Web(ri.er project began #ith the aim to sol.e the Selenium pain,points-
:ump to 788@- The Beijing 6lympics mar' !hinas arri.al as a global po#er+ massi.e mortgage default in the 5nited States triggers the
#orst international recession since the >reat (epression+ The (ar' Anight is .ie#ed by e.ery human ;t#ice<+ still reeling from the untimely
loss of Heath Bedger- But the most important story of that year #as the merging of Selenium and Web(ri.er- Selenium had massi.e
community and commercial support+ but Web(ri.er #as clearly the tool of the future- The joining of the t#o tools pro.ided a common set of
features for all users and brought some of the brightest minds in test automation under one roof- Perhaps the best e%planation for #hy
Web(ri.er and Selenium are merging #as detailed by Simon Ste#art+ the creator of Web(ri.er+ in a joint email to the Web(ri.er and
Selenium community on August =+ 788C-
DWhy are the projects merging? Partly because #ebdri.er addresses some shortcomings in selenium ;by being able to bypass the
:S sandbo%+ for e%ample- And #e.e got a gorgeous API<+ partly because selenium addresses some shortcomings in #ebdri.er
;such as supporting a broader range of bro#sers< and partly because the main selenium contributors and I felt that it #as the best
#ay to offer users the best possible frame#or'-E
Selenium"s Tool Suite
Selenium is composed of multiple soft#are tools- &ach has a specific role-
Selenium # $a%a& Selenium Webdri'er(
Selenium 7 is the future direction of the project and the ne#est addition to the Selenium tool'it- This brand ne# automation tool pro.ides all
sorts of a#esome features+ including a more cohesi.e and object oriented API as #ell as an ans#er to the limitations of the old
implementation-
As you can read in Brief History of The Selenium Project+ both the Selenium and Web(ri.er de.elopers agreed that both tools ha.e
ad.antages and that merging the t#o projects #ould ma'e a much more robust automation tool-
Selenium 7-8 is the product of that effort- It supports the Web(ri.er API and underlying technology+ along #ith the Selenium F technology
underneath the Web(ri.er API for ma%imum fle%ibility in porting your tests- In addition+ Selenium 7 still runs Selenium Fs Selenium 2!
interface for bac'#ards compatibility-
Selenium ) $a%a& Selenium *C or *emote Control(
As you can read in Brief History of The Selenium Project+ Selenium 2! #as the main Selenium project for a long time+ before the
Web(ri.erGSelenium merge brought up Selenium 7+ the ne#est and more po#erful tool-
Selenium F is still acti.ely supported ;mostly in maintenance mode< and pro.ides some features that may not be a.ailable in Selenium 7 for
a #hile+ including support for se.eral languages ;:a.a+ :a.ascript+ 2uby+ PHP+ Python+ Perl and !H< and support for almost e.ery bro#ser out
there-
Selenium I+,
Selenium I(& ;Integrated (e.elopment &n.ironment< is a prototyping tool for building test scripts- It is a $irefo% plugin and pro.ides an
easy,to,use interface for de.eloping automated tests- Selenium I(& has a recording feature+ #hich records user actions as they are performed
and then e%ports them as a reusable script in one of many programming languages that can be later e%ecuted-
Note
&.en though Selenium I(& has a DSa.eE feature that allo#s users to 'eep the tests in a table,based format for later import and e%ecution+ it
is not designed to run your test passes nor is it designed to build all the automated tests you will need- Specifically+ Selenium I(& doesnt
pro.ide iteration or conditional statements for test scripts- At the time of #riting there is no plan to add such thing- The reasons are partly
technical and partly based on the Selenium de.elopers encouraging best practices in test automation #hich al#ays re0uires some amount of
programming- Selenium I+, is simply intended as a rapid prototyping tool- The Selenium de.elopers recommend for serious+ robust test
automation either Selenium 7 or Selenium F to be used #ith one of the many supported programming languages-
Selenium-.rid
Selenium,>rid allo#s the Selenium 2! solution to scale for large test suites and for test suites that must be run in multiple en.ironments-
Selenium >rid allo#s you to run your tests in parallel+ that is+ different tests can be run at the same time on different remote machines- This
has t#o ad.antages- $irst+ if you ha.e a large test suite+ or a slo#,running test suite+ you can boost its performance substantially by using
Selenium >rid to di.ide your test suite to run different tests at the same time using those different machines- Also+ if you must run your test
suite on multiple en.ironments you can ha.e different remote machines supporting and running your tests in them at the same time- In each
case Selenium >rid greatly impro.es the time it ta'es to run your suite by ma'ing use of parallel processing-
Choosing /our Selenium Tool
*any people get started #ith Selenium I(&- If you are not already e%perienced #ith a programming or scripting language you can use
Selenium I(& to get familiar #ith Selenium commands- 5sing the I(& you can create simple tests 0uic'ly+ sometimes #ithin seconds-
We dont+ ho#e.er+ recommend you do all your test automation using Selenium I(&- To effecti.ely use Selenium you #ill need to build and
run your tests using either Selenium 7 or Selenium F in conjunction #ith one of the supported programming languages- Which one you
choose depends on you-
At the time of #riting the Selenium de.elopers are planning on the Selenium,Web(ri.er API being the future direction for Selenium-
Selenium F is pro.ided for bac'#ards compatibility- Still+ both ha.e strengths and #ea'nesses #hich are discussed in the corresponding
chapters of this document-
We recommend those #ho are completely ne# to Selenium to read through these sections- Ho#e.er+ for those #ho are adopting Selenium
for the first time+ and therefore building a ne# test suite from scratch+ you #ill probably #ant to go #ith Selenium 7 since this is the portion
of Selenium that #ill continue to be supported in the future-
Supported Bro0sers and latforms
In Selenium 7-8+ the supported bro#sers .ary depending on #hether you are using Selenium,Web(ri.er or Selenium,2!-
Selenium-Web+ri'er
Selenium,Web(ri.er supports the follo#ing bro#sers along #ith the operating systems these bro#sers are compatible #ith-
>oogle !hrome F7-8-IF7-8J
Internet &%plorer =+ I+ @+ C , K7 and =9,bit #here applicable
$irefo% K-8+ K-L+ K-=+ 9-8+ L-8+ =+ I
6pera FF-LJ
Html5nit 7-C
Android ) 7-KJ for phones and tablets ;de.ices M emulators<
i6S KJ for phones ;de.ices M emulators< and K-7J for tablets ;de.ices M emulators<
Note: At the time of writing there is an emulator bug with Android 2.3 that prevents the driver from working properly on device emulators.
However, it works fine on tablet emulators and real devices.
Selenium )&1 and Selenium-*C&
This is the old+ support platform for Selenium F-8- It should still apply to the Selenium 7-8 release of Selenium,2!-
Bro0ser Selenium
I+,
Selenium
) $*C(
Operating
Systems
2irefo3
4&3
*ecord
and
playbac%
tests
Start
bro0ser5
run tests
Windo0s5
6inu35
7ac
2irefo3 4 *ecord
and
playbac%
tests
Start
bro0ser5
run tests
Windo0s5
6inu35
7ac
2irefo3 # *ecord
and
playbac%
tests
Start
bro0ser5
run tests
Windo0s5
6inu35
7ac
I, 8 Test
e3ecution
only 'ia
Selenium
*C9
Start
bro0ser5
run tests
Windo0s
I, : Test
e3ecution
only 'ia
Selenium
*C9
Start
bro0ser5
run tests
Windo0s
I, ; Test
e3ecution
only 'ia
Selenium
*C9
Start
bro0ser5
run tests
Windo0s
Safari < Test
e3ecution
Start
bro0ser5
Windo0s5
7ac
only 'ia
Selenium
*C
run tests
Safari 4 Test
e3ecution
only 'ia
Selenium
*C
Start
bro0ser5
run tests
Windo0s5
7ac
Safari # Test
e3ecution
only 'ia
Selenium
*C
Start
bro0ser5
run tests
Windo0s5
7ac
Opera
)1
Test
e3ecution
only 'ia
Selenium
*C
Start
bro0ser5
run tests
Windo0s5
6inu35
7ac
Opera = Test
e3ecution
only 'ia
Selenium
*C
Start
bro0ser5
run tests
Windo0s5
6inu35
7ac
Opera 8 Test
e3ecution
only 'ia
Selenium
*C
Start
bro0ser5
run tests
Windo0s5
6inu35
7ac
.oogle
Chrome
Test
e3ecution
only 'ia
Selenium
*C
Start
bro0ser5
run tests
Windo0s5
6inu35
7ac
Others Test artial As
e3ecution
only 'ia
Selenium
*C
support
possible9
9
applicable
9 Tests de'eloped on 2irefo3 'ia Selenium I+, can be e3ecuted on any other supported bro0ser 'ia a simple Selenium *C command
line&
NN Selenium 2! ser.er can start any e%ecutable+ but depending on bro#ser security settings there may be technical limitations that #ould
limit certain features-
2le3ibility and ,3tensibility
"oull find that Selenium is highly fle%ible- There are many #ays you can add functionality to both Selenium test scripts and Seleniums
frame#or' to customi/e your test automation- This is perhaps Seleniums greatest strength #hen compared #ith other automation tools-
These customi/ations are described in .arious places throughout this document- In addition+ since Selenium is 6pen Source+ the sourcecode
can al#ays be do#nloaded and modified-
What"s in this Boo%?
This users guide targets both ne# users and those #ho ha.e already used Selenium but are see'ing additional 'no#ledge- We introduce
Selenium to ne# users and #e do not assume prior Selenium e%perience- We do assume+ ho#e.er+ that the user has at least a basic
understanding of test automation- $or the more e%perienced user+ this guide can act as a reference- $or the more e%perienced+ #e recommend
bro#sing the chapter and subheadings- We.e pro.ided information on the Selenium architecture+ e%amples of common usage+ and a chapter
on test design techni0ues-
The remaining chapters of the reference present1
Selenium I(&
Introduces Selenium I(& and describes ho# to use it to build test scripts- using the Selenium Integrated (e.elopment &n.ironment- If
you are not e%perienced in programming+ but still hoping to learn test automation this is #here you should start and youll find you can
create 0uite a fe# automated tests #ith Selenium I(&- Also+ if you are e%perienced in programming+ this chapter may still interest you
in that you can use Selenium I(& to do rapid prototyping of your tests- This section also demonstrates ho# your test script can be
De%portedE to a programming language for adding more ad.anced capabilities not supported by Selenium I(&-
Selenium 7
&%plains ho# to de.elop an automated test program using Selenium 7-
Selenium F
&%plains ho# to de.elop an automated test program using the Selenium 2! API- *any e%amples are presented in both programming
languages and scripting languages- Also+ the installation and setup of Selenium 2! is co.ered here- The .arious modes+ or
configurations+ that Selenium 2! supports are described+ along #ith their trade,offs and limitations- An architecture diagram is
pro.ided to help illustrate these points- Solutions to common problems fre0uently difficult for ne# Sel,2 users are described here+ for
instance+ handling Security !ertificates+ https re0uests+ pop,ups+ and the opening of ne# #indo#s-
Test (esign !onsiderations
This chapter presents programming techni0ues for use #ith Selenium,Web(ri.er and Selenium 2!- We also demonstrate techni0ues
commonly as'ed about in the user forum such as ho# to design setup and teardo#n functions+ ho# to implement data,dri.en tests
;tests #here one can .ary the data bet#een test passes< and other methods of programming common test automation tas's-
Selenium,>rid
his chapter is not yet developed.
5ser e%tensions
(escribes #ays that Selenium can be modified+ e%tended and customi/ed-
The +ocumentation Team>Authors ast and resent
In alphabetical order+ the follo#ing people ha.e made significant contributions to the authoring of this users guide+ its publishing
infrastructure+ or both- We are .ery grateful to all of them-
(a.e Hunt
Bu'e Inman,Semerau
*ary Ann *ay,Pumphrey
Noah Sussman
Paul >randjean
Peter Ne#hoo'
Santiago Suare/,6rdone/
Simon Ste#art
Tarun Aumar
Ac%no0ledgements
A special than's goes to Patric' Bightbody- As an administrator of the SeleniumH4 #ebsite+ major contributor to Selenium 2!+ his support
#as in.aluable #hen #riting the first release of the users guide- Patric' helped us understand our audience- He also set us up #ith
e.erything #e needed on the seleniumh0-org #ebsite for publishing the documents- Also a than's goes to Andras Hat.ani for his ad.ice on
publishing solutions+ and to Amit Aumar for participating in our discussions and for assisting #ith re.ie#ing the document-
And of course+ #e must recogni!e the "elenium #evelopers- They ha.e truly designed an ama/ing tool- Without the .ision of the original
designers+ and the continued efforts of the current de.elopers+ #e #ould not ha.e such a great tool to pass on to you-
Table Of Contents
Selenium,I(&
Introduction
Installing the I(&
6pening the I(&
I(& $eatures
Building Test !ases
2unning Test !ases
5sing Base 52B to 2un Test !ases in (ifferent (omains
Selenium !ommands ) DSeleneseE
Script Synta%
Test Suites
!ommonly 5sed Selenium !ommands
3erifying Page &lements
Assertion or 3erification?
Bocating &lements
*atching Te%t Patterns
The DAndWaitE !ommands
The #ait$or !ommands in A:AO applications
Se0uence of &.aluation and $lo# !ontrol
Store !ommands and Selenium 3ariables
:a.aScript and Selenese Parameters
echo , The Selenese Print !ommand
Alerts+ Popups+ and *ultiple Windo#s
(ebugging
Writing a Test Suite
5ser &%tensions
$ormat
&%ecuting Selenium,I(& Tests on (ifferent Bro#sers
Troubleshooting
Selenium-I+,
Introduction
The Selenium,I(& ;Integrated (e.elopment &n.ironment< is the tool you use to de.elop your Selenium test cases- Its an easy,to,use
$irefo% plug,in and is generally the most efficient #ay to de.elop test cases- It also contains a conte%t menu that allo#s you to first select a
5I element from the bro#sers currently displayed page and then select from a list of Selenium commands #ith parameters pre,defined
according to the conte%t of the selected 5I element- This is not only a time,sa.er+ but also an e%cellent #ay of learning Selenium script
synta%-
This chapter is all about the Selenium I(& and ho# to use it effecti.ely-
Installing the I+,
5sing $irefo%+ first+ do#nload the I(& from the SeleniumH4 do#nloads page
$irefo% #ill protect you from installing addons from unfamiliar locations+ so you #ill need to clic' ?Allo# to proceed #ith the installation+
as sho#n in the follo#ing screenshot-

When do#nloading from $irefo%+ youll be presented #ith the follo#ing #indo#-

Select Install No#- The $irefo% Add,ons #indo# pops up+ first sho#ing a progress bar+ and #hen the do#nload is complete+ displays the
follo#ing-

2estart $irefo%- After $irefo% reboots you #ill find the Selenium,I(& listed under the $irefo% Tools menu-

Opening the I+,
To run the Selenium,I(&+ simply select it from the $irefo% Tools menu- It opens as follo#s #ith an empty script,editing #indo# and a menu
for loading+ or creating ne# test cases-

I+, 2eatures
7enu Bar
The $ile menu has options for Test !ase and Test Suite ;suite of Test !ases<- 5sing these you can add a ne# Test !ase+ open a Test !ase+
sa.e a Test !ase+ e%port Test !ase in a language of your choice- "ou can also open the recent Test !ase-All these options are also a.ailable
for Test Suite-
The &dit menu allo#s copy+ paste+ delete+ undo+ and select all operations for editing the commands in your test case- The 6ptions menu
allo#s the changing of settings- "ou can set the timeout .alue for certain commands+ add user,defined user e%tensions to the base set of
Selenium commands+ and specify the format ;language< used #hen sa.ing your test cases- The Help menu is the standard $irefo% Help
menuP only one item on this menu)5I,&lement (ocumentation)pertains to Selenium,I(&-
Toolbar
The toolbar contains buttons for controlling the e%ecution of your test cases+ including a step feature for debugging your test cases- The
right,most button+ the one #ith the red,dot+ is the record button-


Speed !ontrol1 controls ho# fast your test case runs-

2un All1 2uns the entire test suite #hen a test suite #ith multiple test cases is loaded-

2un1 2uns the currently selected test- When only a single test is loaded this button and the 2un All button ha.e the same effect-

PauseG2esume1 Allo#s stopping and re,starting of a running test case-

Step1 Allo#s you to DstepE through a test case by running it one command at a time- 5se for debugging test cases-

Test2unner *ode1 Allo#s you to run the test case in a bro#ser loaded #ith the Selenium,!ore Test2unner- The Test2unner is not
commonly used no# and is li'ely to be deprecated- This button is for e.aluating test cases for bac'#ards compatibility #ith the
Test2unner- *ost users #ill probably not need this button-

Apply 2ollup 2ules1 This ad.anced feature allo#s repetiti.e se0uences of Selenium commands to be grouped into a single action-
(etailed documentation on rollup rules can be found in the 5I,&lement (ocumentation on the Help menu-

2ecord1 2ecords the users bro#ser actions-
Test Case ane
"our script is displayed in the test case pane- It has t#o tabs+ one for displaying the command and their parameters in a readable DtableE
format-

The other tab , Source displays the test case in the nati.e format in #hich the file #ill be stored- By default+ this is HT*B although it can be
changed to a programming language such as :a.a or !H+ or a scripting language li'e Python- See the 6ptions menu for details- The Source
.ie# also allo#s one to edit the test case in its ra# form+ including copy+ cut and paste operations-
The !ommand+ Target+ and 3alue entry fields display the currently selected command along #ith its parameters- These are entry fields #here
you can modify the currently selected command- The first parameter specified for a command in the 2eference tab of the bottom pane
al#ays goes in the Target field- If a second parameter is specified by the 2eference tab+ it al#ays goes in the 3alue field-

If you start typing in the !ommand field+ a drop,do#n list #ill be populated based on the first characters you typeP you can then select your
desired command from the drop,do#n-
6og?*eference?@I-,lement?*ollup ane
The bottom pane is used for four different functions)Bog+ 2eference+ 5I,&lement+ and 2ollup)depending on #hich tab is selected-
6og
When you run your test case+ error messages and information messages sho#ing the progress are displayed in this pane automatically+ e.en
if you do not first select the Bog tab- These messages are often useful for test case debugging- Notice the !lear button for clearing the Bog-
Also notice the Info button is a drop,do#n allo#ing selection of different le.els of information to log-

*eference
The 2eference tab is the default selection #hene.er you are entering or modifying Selenese commands and parameters in Table mode- In
Table mode+ the 2eference pane #ill display documentation on the current command- When entering or modifying commands+ #hether from
Table or Source mode+ it is critically important to ensure that the parameters specified in the Target and 3alue fields match those specified in
the parameter list in the 2eference pane- The number of parameters pro.ided must match the number specified+ the order of parameters
pro.ided must match the order specified+ and the type of parameters pro.ided must match the type specified- If there is a mismatch in any of
these three areas+ the command #ill not run correctly-

While the 2eference tab is in.aluable as a 0uic' reference+ it is still often necessary to consult the Selenium 2eference document-
@I-,lement and *ollup
(etailed information on these t#o panes ;#hich co.er ad.anced features< can be found in the 5I,&lement (ocumentation on the Help menu
of Selenium,I(&-
Building Test Cases
There are three primary methods for de.eloping test cases- $re0uently+ a test de.eloper #ill re0uire all three techni0ues-
*ecording
*any first,time users begin by recording a test case from their interactions #ith a #ebsite- When Selenium,I(& is first opened+ the record
button is 6N by default- If you do not #ant Selenium,I(& to begin recording automatically you can turn this off by going under 6ptions Q
6ptions--- and deselecting DStart recording immediately on open-E
(uring recording+ Selenium,I(& #ill automatically insert commands into your test case based on your actions- Typically+ this #ill include1
clic'ing a lin' , click or clickAnd$ait commands
entering .alues , type command
selecting options from a drop,do#n listbo% , select command
clic'ing chec'bo%es or radio buttons , click command
Here are some DgotchasE to be a#are of1
The type command may re0uire clic'ing on some other area of the #eb page for it to record-
$ollo#ing a lin' usually records a click command- "ou #ill often need to change this to clickAnd$ait to ensure your test case pauses
until the ne# page is completely loaded- 6ther#ise+ your test case #ill continue running commands before the page has loaded all its
5I elements- This #ill cause une%pected test case failures-
Adding Aerifications and Asserts With the Conte3t 7enu
"our test cases #ill also need to chec' the properties of a #eb,page- This re0uires assert and verify commands- We #ont describe the
specifics of these commands hereP that is in the chapter on Selenium !ommands ) DSeleneseE- Here #ell simply describe ho# to add them
to your test case-
With Selenium,I(& recording+ go to the bro#ser displaying your test application and right clic' any#here on the page- "ou #ill see a
conte%t menu sho#ing verify andGor assert commands-
The first time you use Selenium+ there may only be one Selenium command listed- As you use the I(& ho#e.er+ you #ill find additional
commands #ill 0uic'ly be added to this menu- Selenium,I(& #ill attempt to predict #hat command+ along #ith the parameters+ you #ill
need for a selected 5I element on the current #eb,page-
Bets see ho# this #or's- 6pen a #eb,page of your choosing and select a bloc' of te%t on the page- A paragraph or a heading #ill #or' fine-
No#+ right,clic' the selected te%t- The conte%t menu should gi.e you a verifye%t&resent command and the suggested parameter should be
the te%t itself-
Also+ notice the Sho# All A.ailable !ommands menu option- This sho#s many+ many more commands+ again+ along #ith suggested
parameters+ for testing your currently selected 5I element-
Try a fe# more 5I elements- Try right,clic'ing an image+ or a user control li'e a button or a chec'bo%- "ou may need to use Sho# All
A.ailable !ommands to see options other than verifye%t&resent- 6nce you select these other options+ the more commonly used ones #ill
sho# up on the primary conte%t menu- $or e%ample+ selecting verify'lement&resent for an image should later cause that command to be
a.ailable on the primary conte%t menu the ne%t time you select an image and right,clic'-
Again+ these commands #ill be e%plained in detail in the chapter on Selenium commands- $or no# though+ feel free to use the I(& to record
and select commands into a test case and then run it- "ou can learn a lot about the Selenium commands simply by e%perimenting #ith the
I(&-
,diting
Insert Command
Table Aie0
Select the point in your test case #here you #ant to insert the command- To do this+ in the Test !ase Pane+ left,clic' on the line #here you
#ant to insert a ne# command- 2ight,clic' and select Insert !ommandP the I(& #ill add a blan' line just ahead of the line you selected-
No# use the command editing te%t fields to enter your ne# command and its parameters-
Source Aie0
Select the point in your test case #here you #ant to insert the command- To do this+ in the Test !ase Pane+ left,clic' bet#een the commands
#here you #ant to insert a ne# command+ and enter the HT*B tags needed to create a K,column ro# containing the !ommand+ first
parameter ;if one is re0uired by the !ommand<+ and second parameter ;again+ if one is re0uired to locate an element< and third
parameter;again+ if one is re0uired to ha.e a .alue<- &%ample1
<tr>
<td>Command</td>
<td>target (locator)</td>
<td>Value</td>
</tr>
Insert Comment
!omments may be added to ma'e your test case more readable- These comments are ignored #hen the test case is run-
!omments may also be used to add .ertical #hite space ;one or more blan' lines< in your testsP just create empty comments- An empty
command #ill cause an error during e%ecutionP an empty comment #ont-
Table Aie0
Select the line in your test case #here you #ant to insert the comment- 2ight,clic' and select Insert !omment- No# use the !ommand field
to enter the comment- "our comment #ill appear in purple te%t-
Source Aie0
Select the point in your test case #here you #ant to insert the comment- Add an HT*B,style comment+ i-e-+ <!-- your comment
here -->-
,dit a Command or Comment
Table Aie0
Simply select the line to be changed and edit it using the !ommand+ Target+ and 3alue fields-
Source Aie0
Since Source .ie# pro.ides the e0ui.alent of a W"SIW"> ;What "ou See is What "ou >et< editor+ simply modify #hich line you #ish)
command+ parameter+ or comment-
Opening and Sa'ing a Test Case
Bi'e most programs+ there are Sa.e and 6pen commands under the $ile menu- Ho#e.er+ Selenium distinguishes bet#een test cases and test
suites- To sa.e your Selenium,I(& tests for later use you can either sa.e the indi.idual test cases+ or sa.e the test suite- If the test cases of
your test suite ha.e not been sa.ed+ youll be prompted to sa.e them before sa.ing the test suite-
When you open an e%isting test case or suite+ Selenium,I(& displays its Selenium commands in the Test !ase Pane-
*unning Test Cases
The I(& allo#s many options for running your test case- "ou can run a test case all at once+ stop and start it+ run it one line at a time+ run a
single command you are currently de.eloping+ and you can do a batch run of an entire test suite- &%ecution of test cases is .ery fle%ible in
the I(&-
2un a Test !ase
!lic' the 2un button to run the currently displayed test case-
2un a Test Suite
!lic' the 2un All button to run all the test cases in the currently loaded test suite-
Stop and Start
The Pause button can be used to stop the test case #hile it is running- The icon of this button then changes to indicate the 2esume
button- To continue clic' 2esume-
Stop in the *iddle
"ou can set a brea'point in the test case to cause it to stop on a particular command- This is useful for debugging your test case- To set
a brea'point+ select a command+ right,clic'+ and from the conte%t menu select Toggle Brea'point-
Start from the *iddle
"ou can tell the I(& to begin running from a specific command in the middle of the test case- This also is used for debugging- To set a
startpoint+ select a command+ right,clic'+ and from the conte%t menu select SetG!lear Start Point-
2un Any Single !ommand
(ouble,clic' any single command to run it by itself- This is useful #hen #riting a single command- It lets you immediately test a
command you are constructing+ #hen you are not sure if it is correct- "ou can double,clic' it to see if it runs correctly- This is also
a.ailable from the conte%t menu-
@sing Base @*6 to *un Test Cases in +ifferent +omains
The (ase )*+ field at the top of the Selenium,I(& #indo# is .ery useful for allo#ing test cases to be run across different domains-
Suppose that a site named http1GGne#s-portal-com had an in,house beta site named http1GGbeta-ne#s-portal-com- Any test cases for these sites
that begin #ith an open statement should specify a relative )*+ as the argument to open rather than an absolute )*+ ;one starting #ith a
protocol such as http1 or https1<- Selenium,I(& #ill then create an absolute 52B by appending the open commands argument onto the end
of the .alue of Base 52B- $or e%ample+ the test case belo# #ould be run against http1GGne#s-portal-comGabout-html1

This same test case #ith a modified Base 52B setting #ould be run against http1GGbeta-ne#s-portal-comGabout-html1

Selenium Commands > BSeleneseC
Selenium commands+ often called selenese+ are the set of commands that run your tests- A se0uence of these commands is a test script- Here
#e e%plain those commands in detail+ and #e present the many choices you ha.e in testing your #eb application #hen using Selenium-
Selenium pro.ides a rich set of commands for fully testing your #eb,app in .irtually any #ay you can imagine- The command set is often
called selenese- These commands essentially create a testing language-
In selenese+ one can test the e%istence of 5I elements based on their HT*B tags+ test for specific content+ test for bro'en lin's+ input fields+
selection list options+ submitting forms+ and table data among other things- In addition Selenium commands support testing of #indo# si/e+
mouse position+ alerts+ Aja% functionality+ pop up #indo#s+ e.ent handling+ and many other #eb,application features- The !ommand
2eference lists all the a.ailable commands-
A command tells Selenium #hat to do- Selenium commands come in three Dfla.orsE1 Actions+ Accessors+ and Assertions-
Actions are commands that generally manipulate the state of the application- They do things li'e Dclic' this lin'E and Dselect that
optionE- If an Action fails+ or has an error+ the e%ecution of the current test is stopped-
*any Actions can be called #ith the DAndWaitE suffi%+ e-g- Dclic'AndWaitE- This suffi% tells Selenium that the action #ill cause the
bro#ser to ma'e a call to the ser.er+ and that Selenium should #ait for a ne# page to load-
Accessors e%amine the state of the application and store the results in .ariables+ e-g- DstoreTitleE- They are also used to automatically
generate Assertions-
Assertions are li'e Accessors+ but they .erify that the state of the application conforms to #hat is e%pected- &%amples include Dma'e
sure the page title is OE and D.erify that this chec'bo% is chec'edE-
All Selenium Assertions can be used in K modes1 DassertE+ D.erifyE+ and E #ait$orE- $or e%ample+ you can DassertTe%tE+ D.erifyTe%tE
and D#ait$orTe%tE- When an DassertE fails+ the test is aborted- When a D.erifyE fails+ the test #ill continue e%ecution+ logging the
failure- This allo#s a single DassertE to ensure that the application is on the correct page+ follo#ed by a bunch of D.erifyE assertions to
test form field .alues+ labels+ etc-
D#ait$orE commands #ait for some condition to become true ;#hich can be useful for testing Aja% applications<- They #ill succeed
immediately if the condition is already true- Ho#e.er+ they #ill fail and halt the test if the condition does not become true #ithin the
current timeout setting ;see the setTimeout action belo#<-
Script Synta3
Selenium commands are simple+ they consist of the command and t#o parameters- $or e%ample1
.erifyTe%t GGdi.GG
aR7S
Bogin
The parameters are not al#ays re0uiredP it depends on the command- In some cases both are re0uired+ in others one parameter is re0uired+
and in still others the command may ta'e no parameters at all- Here are a couple more e%amples1
goBac'AndWait
.erifyTe%tPresent Welcome
to *y
Home
Page
type idTphon
e
;LLL<
===,I8==
type idTaddre
ssF
The command reference describes the parameter re0uirements for each command-
Parameters .ary+ ho#e.er they are typically1
a locator for identifying a 5I element #ithin a page-
a te%t pattern for .erifying or asserting e%pected page content
a te%t pattern or a selenium .ariable for entering te%t in an input field or for selecting an option from an option list-
Bocators+ te%t patterns+ selenium .ariables+ and the commands themsel.es are described in considerable detail in the section on Selenium
!ommands-
Selenium scripts that #ill be run from Selenium,I(& #ill be be stored in an HT*B te%t file format- This consists of an HT*B table #ith
three columns- The first column identifies the Selenium command+ the second is a target+ and the final column contains a .alue- The second
and third columns may not re0uire .alues depending on the chosen Selenium command+ but they should be present- &ach table ro#
represents a ne# Selenium command- Here is an e%ample of a test that opens a page+ asserts the page title and then .erifies some content on
the page1
<table>
<tr><td>open</td><td>/download/</td><td></td></tr>
<tr><td>assertTitle</td><td></td><td>Downloads</td></tr>
<tr><td>eri!yTe"t</td><td>//h#</td><td>Downloads</td></tr>
</table>
2endered as a table in a bro#ser this #ould loo' li'e the follo#ing1
open G
do#nloadG

assertTitle (o#nloads
.erifyTe%t GGh7 (o#nloads
The Selenese HT*B synta% can be used to #rite and run tests #ithout re0uiring 'no#ledge of a programming language- With a basic
'no#ledge of selenese and Selenium,I(& you can 0uic'ly produce and run testcases-
Test Suites
A test suite is a collection of tests- 6ften one #ill run all the tests in a test suite as one continuous batch,job-
When using Selenium,I(&+ test suites also can be defined using a simple HT*B file- The synta% again is simple- An HT*B table defines a
list of tests #here each ro# defines the filesystem path to each test- An e%ample tells it all-
<html>
<head>
<title>Test $uite %unction Tests - &riority '</title>
</head>
<body>
<table>
<tr><td><b>$uite (! Tests</b></td></tr>
<tr><td><a hre!)*+/,ogin+html*>,ogin</a></td></tr>
<tr><td><a hre!)*+/$earchValues+html*>Test $earching !or Values</a></td></tr>
<tr><td><a hre!)*+/$aeValues+html*>Test $ae</a></td></tr>
</table>
</body>
</html>
A file similar to this #ould allo# running the tests all at once+ one after another+ from the Selenium,I(&-
Test suites can also be maintained #hen using Selenium,2!- This is done .ia programming and can be done a number of #ays- !ommonly
:unit is used to maintain a test suite if one is using Selenium,2! #ith :a.a- Additionally+ if !H is the chosen language+ Nunit could be
employed- If using an interpreted language li'e Python #ith Selenium,2! then some simple programming #ould be in.ol.ed in setting up a
test suite- Since the #hole reason for using Selenium,2! is to ma'e use of programming logic for your testing this usually isnt a problem-
Commonly @sed Selenium Commands
To conclude our introduction of Selenium+ #ell sho# you a fe# typical Selenium commands- These are probably the most commonly used
commands for building tests-
open
opens a page using a 52B-
clic'Gclic'AndWait
performs a clic' operation+ and optionally #aits for a ne# page to load-
.erifyTitleGassertTitle
.erifies an e%pected page title-
.erifyTe%tPresent
.erifies e%pected te%t is some#here on the page-
.erify&lementPresent
.erifies an e%pected 5I element+ as defined by its HT*B tag+ is present on the page-
.erifyTe%t
.erifies e%pected te%t and its corresponding HT*B tag are present on the page-
.erifyTable
.erifies a tables e%pected contents-
#ait$orPageToBoad
pauses e%ecution until an e%pected ne# page loads- !alled automatically #hen clic'AndWait is used-
#ait$or&lementPresent
pauses e%ecution until an e%pected 5I element+ as defined by its HT*B tag+ is present on the page-
Aerifying age ,lements
3erifying 5I elements on a #eb page is probably the most common feature of your automated tests- Selenese allo#s multiple #ays of
chec'ing for 5I elements- It is important that you understand these different methods because these methods define #hat you are actually
testing-
$or e%ample+ #ill you test that---
F- an element is present some#here on the page?
7- specific te%t is some#here on the page?
K- specific te%t is at a specific location on the page?
$or e%ample+ if you are testing a te%t heading+ the te%t and its position at the top of the page are probably rele.ant for your test- If+ ho#e.er+
you are testing for the e%istence of an image on the home page+ and the #eb designers fre0uently change the specific image file along #ith
its position on the page+ then you only #ant to test that an image ;as opposed to the specific image file< e%ists somewhere on the page-
Assertion or Aerification?
!hoosing bet#een DassertE and D.erifyE comes do#n to con.enience and management of failures- Theres .ery little point chec'ing that the
first paragraph on the page is the correct one if your test has already failed #hen chec'ing that the bro#ser is displaying the e%pected page-
If youre not on the correct page+ youll probably #ant to abort your test case so that you can in.estigate the cause and fi% the issue;s<
promptly- 6n the other hand+ you may #ant to chec' many attributes of a page #ithout aborting the test case on the first failure as this #ill
allo# you to re.ie# all failures on the page and ta'e the appropriate action- &ffecti.ely an DassertE #ill fail the test and abort the current test
case+ #hereas a D.erifyE #ill fail the test and continue to run the test case-
The best use of this feature is to logically group your test commands+ and start each group #ith an DassertE follo#ed by one or more D.erifyE
test commands- An e%ample follo#s1
Command Target Aalue
open ?do0nload?
assertTitle +o0nloads
Command Target Aalue
'erifyTe3t ??h# +o0nloads
assertTable )&#&) Selenium
I+,
'erifyTable )&#&# Dune 45
#118
'erifyTable )&#&4 )&1 beta #
The abo'e e3ample first opens a page and then BassertsC that the correct page is loaded by comparing the title 0ith the e3pected
'alue& Only if this passes 0ill the follo0ing command run and B'erifyC that the te3t is present in the e3pected location& The test case
then BassertsC the first column in the second ro0 of the first table contains the e3pected 'alue5 and only if this passed 0ill the
remaining cells in that ro0 be B'erifiedC&
'erifyTe3tresent
The command eri!yTe"t&resent is used to .erify specific te%t e%ists somewhere on the page- It ta'es a single argument)the te%t
pattern to be .erified- $or e%ample1
Command Target Aalue
'erifyTe3tresen
t
7ar%etin
g Analysis

This 0ould cause Selenium to search for5 and 'erify5 that the te3t string B7ar%eting AnalysisC appears some0here on the page
currently being tested& @se eri!yTe"t&resent 0hen you are interested in only the te3t itself being present on the page& +o not
use this 0hen you also need to test 0here the te3t occurs on the page&
'erify,lementresent
5se this command #hen you must test for the presence of a specific 5I element+ rather than its content- This .erification does not chec' the
te%t+ only the HT*B tag- 6ne common use is to chec' for the presence of an image-
Command Target Aalue
'erify,lementrese
nt
??di'?p?
img

This command 'erifies that an image5 specified by the e3istence of an EimgF HT76 tag5 is present on the page5 and that it follo0s a
Edi'F tag and a EpF tag& The first $and only( parameter is a locator for telling the Selenese command ho0 to find the element&
6ocators are e3plained in the ne3t section&
eri!y-lement&resent can be used to chec' the e%istence of any HT*B tag #ithin the page- "ou can chec' the e%istence of lin's+
paragraphs+ di.isions Udi.Q+ etc- Here are a fe# more e%amples-
Command Target Aalue
'erify,lementrese
nt
??di'?p
'erify,lementrese
nt
??di'?a
'erify,lementrese
nt
idG6ogin
'erify,lementrese
nt
lin%G.o
to
7ar%etin
g
*esearch

'erify,lementrese
nt
??aH#I
'erify,lementrese
nt
??head?titl
e

These e3amples illustrate the 'ariety of 0ays a @I element may be tested& Again5 locators are e3plained in the ne3t section&
'erifyTe3t
5se eri!yTe"t #hen both the te%t and its 5I element must be tested- eri!yTe"t must use a locator- If you choose an ,&ath or
#-. locator+ you can .erify that specific te%t appears at a specific location on the page relati.e to other 5I components on the page-
Command Target Aalue
'erifyTe3t ??table?
tr?td?di
'?p
This is my
te3t and it
occurs
right after
the di'
inside the
table&
6ocating ,lements
$or many Selenium commands+ a target is re0uired- This target identifies an element in the content of the #eb application+ and consists of the
location strategy follo#ed by the location in the format locatorType)location- The locator type can be omitted in many cases- The
.arious locator types are e%plained belo# #ith e%amples for each-
6ocating by Identifier
This is probably the most common method of locating elements and is the catch,all default #hen no recogni/ed locator type is used- With
this strategy+ the first element #ith the id attribute .alue matching the location #ill be used- If no element has a matching id attribute+ then
the first element #ith a name attribute matching the location #ill be used-
$or instance+ your page source could ha.e id and name attributes as follo#s1
'
#
.
/
0
1
2
3
4
<html>
<body>
<!orm id)*login%orm*>
<input name)*username* type)*te"t* />
<input name)*password* type)*password* />
<input name)*continue* type)*submit* alue)*,ogin* />
</!orm>
</body>
<html>
The follo#ing locator strategies #ould return the elements from the HT*B snippet abo.e indicated by line number1
identi!ier)login%orm ;K<
identi!ier)password ;L<
identi!ier)continue ;=<
continue ;=<
Since the identi!ier type of locator is the default+ the identi!ier) in the first three e%amples abo.e is not necessary-
6ocating by Id
This type of locator is more limited than the identifier locator type+ but also more e%plicit- 5se this #hen you 'no# an elements id attribute-
'
#
.
<html>
<body>
<!orm id)*login%orm*>
/
0
1
2
3
4
'5
<input name)*username* type)*te"t* />
<input name)*password* type)*password* />
<input name)*continue* type)*submit* alue)*,ogin* />
<input name)*continue* type)*button* alue)*Clear* />
</!orm>
</body>
<html>
idTlogin$orm ;K<
6ocating by Name
The name locator type #ill locate the first element #ith a matching name attribute- If multiple elements ha.e the same .alue for a name
attribute+ then you can use filters to further refine your location strategy- The default filter type is .alue ;matching the .alue attribute<-
'
#
.
/
0
1
2
3
4
'5
<html>
<body>
<!orm id)*login%orm*>
<input name)*username* type)*te"t* />
<input name)*password* type)*password* />
<input name)*continue* type)*submit* alue)*,ogin* />
<input name)*continue* type)*button* alue)*Clear* />
</!orm>
</body>
<html>
nameTusername ;9<
name)continue alue)Clear ;I<
name)continue Clear ;I<
name)continue type)button ;I<
Note
5nli'e some types of OPath and (6* locators+ the three types of locators abo.e allo# Selenium to test a 5I element independent of its
location on the page- So if the page structure and organi/ation is altered+ the test #ill still pass- "ou may or may not #ant to also test #hether
the page structure changes- In the case #here #eb designers fre0uently alter the page+ but its functionality must be regression tested+ testing
.ia id and name attributes+ or really .ia any HT*B property+ becomes .ery important-
6ocating by Jath
OPath is the language used for locating nodes in an O*B document- As HT*B can be an implementation of O*B ;OHT*B<+ Selenium
users can le.erage this po#erful language to target elements in their #eb applications- OPath e%tends beyond ;as #ell as supporting< the
simple methods of locating by id or name attributes+ and opens up all sorts of ne# possibilities such as locating the third chec'bo% on the
page-
6ne of the main reasons for using OPath is #hen you dont ha.e a suitable id or name attribute for the element you #ish to locate- "ou can
use OPath to either locate the element in absolute terms ;not ad.ised<+ or relati.e to an element that does ha.e an id or name attribute- OPath
locators can also be used to specify elements .ia attributes other than id and name-
Absolute OPaths contain the location of all elements from the root ;html< and as a result are li'ely to fail #ith only the slightest adjustment
to the application- By finding a nearby element #ith an id or name attribute ;ideally a parent element< you can locate your target element
based on the relationship- This is much less li'ely to change and can ma'e your tests more robust-
Since only "path locators start #ith DGGE+ it is not necessary to include the "path) label #hen specifying an OPath locator-
'
#
.
/
0
1
2
3
4
'5
<html>
<body>
<!orm id)*login%orm*>
<input name)*username* type)*te"t* />
<input name)*password* type)*password* />
<input name)*continue* type)*submit* alue)*,ogin* />
<input name)*continue* type)*button* alue)*Clear* />
</!orm>
</body>
<html>
%pathTGhtmlGbodyGformRFS ;K< , Absolute path /would break if the H.+ was changed only slightly0
//!orm6'7 ;K< , 1irst form element in the H.+
"path)//!orm68id)9login%orm97 ;K< , he form element with attribute named 2id3 and the value 2login1orm3
"path)//!orm6input/8name)9username97 ;K< , 1irst form element with an input child element with attribute named
2name3 and the value 2username3
//input68name)9username97 ;9< , 1irst input element with attribute named 2name3 and the value 2username3
//!orm68id)9login%orm97/input6'7 ;9< , 1irst input child element of the form element with attribute named 2id3 and the
value 2login1orm3
//input68name)9continue9768type)9button97 ;I< , 4nput with attribute named 2name3 and the value 2continue3 and
attribute named 2type3 and the value 2button3
//!orm68id)9login%orm97/input6/7 ;I< , 1ourth input child element of the form element with attribute named 2id3 and
value 2login1orm3
These e%amples co.er some basics+ but in order to learn more+ the follo#ing references are recommended1
WKSchools OPath Tutorial
WK! OPath 2ecommendation
There are also a couple of .ery useful $irefo% Add,ons that can assist in disco.ering the OPath of an element1
OPath !hec'er , suggests OPath and can be used to test OPath results-
$irebug , OPath suggestions are just one of the many po#erful features of this .ery useful add,on-
6ocating Hyperlin%s by 6in% Te3t
This is a simple method of locating a hyperlin' in your #eb page by using the te%t of the lin'- If t#o lin's #ith the same te%t are present+
then the first match #ill be used-
'
#
.
/
0
1
2
<html>
<body>
<p>:re you sure you want to do this;</p>
<a hre!)*continue+html*>Continue</a>
<a hre!)*cancel+html*>Cancel</a>
</body>
<html>
lin'T!ontinue ;9<
lin<)Cancel ;L<
6ocating by +O7
The (ocument 6bject *odel represents an HT*B document and can be accessed using :a.aScript- This location strategy ta'es :a.aScript
that e.aluates to an element on the page+ #hich can be simply the elements location using the hierarchical dotted notation-
Since only dom locators start #ith DdocumentE+ it is not necessary to include the dom) label #hen specifying a (6* locator-
'
#
.
/
0
1
<html>
<body>
<!orm id)*login%orm*>
<input name)*username* type)*te"t* />
<input name)*password* type)*password* />
<input name)*continue* type)*submit* alue)*,ogin* />
2
3
4
'5
<input name)*continue* type)*button* alue)*Clear* />
</!orm>
</body>
<html>
domTdocument-get&lementById;Vlogin$ormV< ;K<
dom)document+!orms69login%orm97 ;K<
dom)document+!orms657 ;K<
document+!orms657+username ;9<
document+!orms657+elements69username97 ;9<
document+!orms657+elements657 ;9<
document+!orms657+elements6.7 ;I<
"ou can use Selenium itself as #ell as other sites and e%tensions to e%plore the (6* of your #eb application- A good reference e%ists on
WKSchools-
6ocating by CSS
!SS ;!ascading Style Sheets< is a language for describing the rendering of HT*B and O*B documents- !SS uses Selectors for binding
style properties to elements in the document- These Selectors can be used by Selenium as another locating strategy-
'
#
.
/
0
1
2
3
4
'5
<html>
<body>
<!orm id)*login%orm*>
<input class)*re=uired* name)*username* type)*te"t* />
<input class)*re=uired pass!ield* name)*password* type)*password* />
<input name)*continue* type)*submit* alue)*,ogin* />
<input name)*continue* type)*button* alue)*Clear* />
</!orm>
</body>
<html>
cssTformHlogin$orm ;K<
css)input6name)*username*7 ;9<
css)input+re=uired6type)*te"t*7 ;9<
css)input+pass!ield ;L<
css)>login%orm input6type)*button*7 ;I<
css)>login%orm input?nth-child(#) ;L<
$or more information about !SS Selectors+ the best place to go is the WK! publication- "oull find additional references there-
Note
*ost e%perienced Selenium users recommend !SS as their locating strategy of choice as its considerably faster than OPath and can find the
most complicated objects in an intrinsic HT*B document-
Implicit 6ocators
"ou can choose to omit the locator type in the follo#ing situations1
Bocators #ithout an e%plicitly defined locator strategy #ill default to using the identifier locator strategy- See Bocating by
Identifier-
Bocators starting #ith DGGE #ill use the OPath locator strategy- See Bocating by OPath-
Bocators starting #ith DdocumentE #ill use the (6* locator strategy- See Bocating by (6*
7atching Te3t atterns
Bi'e locators+ patterns are a type of parameter fre0uently re0uired by Selenese commands- &%amples of commands #hich re0uire patterns
are 'erifyTe3tresent+ 'erifyTitle+ 'erifyAlert+ assertConfirmation+ 'erifyTe3t+ and 'erifyrompt- And as has been mentioned abo.e+
lin' locators can utili/e a pattern- Patterns allo# you to describe+ .ia the use of special characters+ #hat te%t is e%pected rather than ha.ing to
specify that te%t e%actly-
There are three types of patterns1 globbing+ regular e%pressions+ and e%act-
.lobbing atterns
*ost people are familiar #ith globbing as it is utili/ed in filename e%pansion at a (6S or 5ni%GBinu% command line such as ls @+c- In
this case+ globbing is used to display all the files ending #ith a +c e%tension that e%ist in the current directory- >lobbing is fairly limited-
6nly t#o special characters are supported in the Selenium implementation1
9 #hich translates to Dmatch anything+E i-e-+ nothing+ a single character+ or many characters-
H I ;character class< #hich translates to Dmatch any single character found inside the s0uare brac'ets-E A dash ;hyphen< can be
used as a shorthand to specify a range of characters ;#hich are contiguous in the AS!II character set<- A fe# e%amples #ill ma'e
the functionality of a character class clear1
6aeiou7 matches any lo#ercase .o#el
65-47 matches any digit
6a-A:-B5-47 matches any alphanumeric character
In most other conte%ts+ globbing includes a third special character+ the ?- Ho#e.er+ Selenium globbing patterns only support the asteris' and
character class-
To specify a globbing pattern parameter for a Selenese command+ you can prefi% the pattern #ith a globK label- Ho#e.er+ because globbing
patterns are the default+ you can also omit the label and specify just the pattern itself-
Belo# is an e%ample of t#o commands that use globbing patterns- The actual lin' te%t on the page being tested #as D$ilmGTele.ision
(epartmentEP by using a pattern rather than the e%act te%t+ the clic% command #ill #or' e.en if the lin' te%t is changed to D$ilm M
Tele.ision (epartmentE or D$ilm and Tele.ision (epartmentE- The glob patterns asteris' #ill match Danything or nothingE bet#een the
#ord D$ilmE and the #ord DTele.isionE-
Command Target Aalue
clic% lin%GglobK
2ilm9Tele'
ision
+epartmen
t

'erifyTitle globK92ilm
9Tele'ision
9

The actual title of the page reached by clic%ing on the lin% 0as B+e AnLa 2ilm And Tele'ision +epartment - 7enuC& By using a
pattern rather than the e3act te3t5 the eri!yTitle 0ill pass as long as the t0o 0ords B2ilmC and BTele'isionC appear $in that
order( any0here in the page"s title& 2or e3ample5 if the page"s o0ner should shorten the title to !ust B2ilm M Tele'ision +epartment5C
the test 0ould still pass& @sing a pattern for both a lin% and a simple test that the lin% 0or%ed $such as the eri!yTitle abo'e
does( can greatly reduce the maintenance for such test cases&
*egular ,3pression atterns
*egular e%pression patterns are the most po#erful of the three types of patterns that Selenese supports- 2egular e%pressions are also
supported by most high,le.el programming languages+ many te%t editors+ and a host of tools+ including the Binu%G5ni% command,line
utilities grep+ sed+ and a0%- In Selenese+ regular e%pression patterns allo# a user to perform many tas's that #ould be .ery difficult
other#ise- $or e%ample+ suppose your test needed to ensure that a particular table cell contained nothing but a number- rege"p? 65-47C
is a simple pattern that #ill match a decimal number of any length-
Whereas Selenese globbing patterns support only the 9 and H I ;character class< features+ Selenese regular e%pression patterns offer the same
#ide array of special characters that e%ist in :a.aScript- Belo# are a subset of those special characters1
ATT,*N 7ATCH
- any single
character
R S character
class1 any
single
character that
appears
inside the
brac'ets
N 0uantifier1 8
or more of
the preceding
character ;or
group<
J 0uantifier1 F
or more of
the preceding
character ;or
group<
? 0uantifier1 8
or F of the
preceding
character ;or
group<
WF+LX 0uantifier1 F
through L of
the preceding
character ;or
ATT,*N 7ATCH
group<
Y alternation1
the
characterGgro
up on the left
or the
characterGgro
up on the
right
; < grouping1
often used
#ith
alternation
andGor
0uantifier
2egular e%pression patterns in Selenese need to be prefi%ed #ith either rege"p? or rege"pi?- The former is case,sensiti.eP the latter is
case,insensiti.e-
A fe# e%amples #ill help clarify ho# regular e%pression patterns can be used #ith Selenese commands- The first one uses #hat is probably
the most commonly used regular e%pression pattern)&9 ;Ddot starE<- This t#o,character se0uence can be translated as D8 or more occurrences
of any characterE or more simply+ Danything or nothing-E It is the e0ui.alent of the one,character globbing pattern 9 ;a single asteris'<-
Command Target Aalue
clic% lin%Grege3
pK2ilm&9Te
le'ision
+epartmen
t

'erifyTitle rege3pK&92i
lm&9Tele'is
ion&9

The e3ample abo'e is functionally eNui'alent to the earlier e3ample that used globbing patterns for this same test& The only
differences are the prefi3 $rege3pK instead of globK( and the Banything or nothingC pattern $&9 instead of !ust 9(&
The more comple% e%ample belo# tests that the "ahooZ Weather page for Anchorage+ Alas'a contains info on the sunrise time1
Command Target Aalue
open http1GG#eather-yahoo-
comGforecastG5SAA8
8F7-html

'erifyTe3tresen
t
rege3pKSunriseK 9H1-
=IO)5#PKH1-=IO#P
HapIm

6et"s e3amine the regular e3pression abo'e one part at a timeK
$unrise
? @
The
string
SunriseK
!ollowed
by 5 or
more
spaces
65-47
D'E#F
' or #
digits
(!or the
hour o!
the day)
? The
characte
r K (no
special
characte
rs
inoled
)
65-47
D#F
# digits
(!or the
minutes)
!ollowed
by a
space
6ap7m GaH or
GpH
!ollowed
by GmH
(am or
pm)
Exact Patterns
The e3act type of Selenium pattern is of marginal usefulness- It uses no special characters at all- So+ if you needed to loo' for an actual
asteris' character ;#hich is special for both globbing and regular e%pression patterns<+ the e3act pattern #ould be one #ay to do that- $or
e%ample+ if you #anted to select an item labeled D2eal NE from a dropdo#n+ the follo#ing code might #or' or it might not- The asteris' in
the glob?Ieal @ pattern #ill match anything or nothing- So+ if there #as an earlier select option labeled D2eal Numbers+E it #ould be the
option selected rather than the D2eal NE option-
select GGselect glob1
2eal
N
In order to ensure that the D2eal NE item #ould be selected+ the e"act? prefi% could be used to create an e3act pattern as sho#n belo#1
select GGselect e%act1
2eal N
But the same effect could be achie.ed .ia escaping the asteris' in a regular e%pression pattern1
select GGselect rege%p1
2eal [N
Its rather unli'ely that most testers #ill e.er need to loo' for an asteris' or a set of s0uare brac'ets #ith characters inside them ;the
character class for globbing patterns<- Thus+ globbing patterns and regular e%pression patterns are sufficient for the .ast majority of us-
The BAndWaitC Commands
The difference bet#een a command and its And$ait alternati.e is that the regular command ;e-g- click< #ill do the action and continue #ith
the follo#ing command as fast as it can+ #hile the And$ait alternati.e ;e-g- clickAnd$ait< tells Selenium to 0ait for the page to load after
the action has been done-
The And$ait alternati.e is al#ays used #hen the action causes the bro#ser to na.igate to another page or reload the present one-
Be a#are+ if you use an And$ait command for an action that does not trigger a na.igationGrefresh+ your test #ill fail- This happens because
Selenium #ill reach the And$ait?s timeout #ithout seeing any na.igation or refresh being made+ causing Selenium to raise a timeout
e%ception-
The 0ait2or Commands in ADAJ applications
In A:AO dri.en #eb applications+ data is retrie.ed from ser.er #ithout refreshing the page- 5sing and$ait commands #ill not #or' as the
page is not actually refreshed- Pausing the test e%ecution for a certain period of time is also not a good approach as #eb element might
appear later or earlier than the stipulated period depending on the systems responsi.eness+ load or other uncontrolled factors of the moment+
leading to test failures- The best approach #ould be to #ait for the needed element in a dynamic period and then continue the e%ecution as
soon as the element is found-
This is done using wait1or commands+ as wait1or'lement&resent or wait1or5isible+ #hich #ait dynamically+ chec'ing for the desired
condition e.ery second and continuing to the ne%t command in the script as soon as the condition is met-
SeNuence of ,'aluation and 2lo0 Control
When a script runs+ it simply runs in se0uence+ one command after another-
Selenese+ by itself+ does not support condition statements ;if,else+ etc-< or iteration ;for+ #hile+ etc-<- *any useful tests can be conducted
#ithout flo# control- Ho#e.er+ for a functional test of dynamic content+ possibly in.ol.ing multiple pages+ programming logic is often
needed-
When flo# control is needed+ there are three options1
F- 2un the script using Selenium,2! and a client library such as :a.a or PHP to utili/e the programming languages flo# control
features-
7- 2un a small :a.aScript snippet from #ithin the script using the store&.al command-
K- Install the goto\sel\ide-js e%tension-
*ost testers #ill e%port the test script into a programming language file that uses the Selenium,2! API ;see the Selenium,I(& chapter<-
Ho#e.er+ some organi/ations prefer to run their scripts from Selenium,I(& #hene.er possible ;for instance+ #hen they ha.e many junior,
le.el people running tests for them+ or #hen programming s'ills are lac'ing<- If this is your case+ consider a :a.aScript snippet or the
goto\sel\ide-js e%tension-
Store Commands and Selenium Aariables
"ou can use Selenium .ariables to store constants at the beginning of a script- Also+ #hen combined #ith a data,dri.en test design ;discussed
in a later section<+ Selenium .ariables can be used to store .alues passed to your test program from the command,line+ from another
program+ or from a file-
The plain store command is the most basic of the many store commands and can be used to simply store a constant .alue in a selenium
.ariable- It ta'es t#o parameters+ the te%t .alue to be stored and a selenium .ariable- 5se the standard .ariable naming con.entions of only
alphanumeric characters #hen choosing a name for your .ariable-
Command Target Aalue
store paul]mysite-org userName
6ater in your script5 you"ll 0ant to use the stored 'alue of your 'ariable& To access the 'alue of a 'ariable5 enclose the 'ariable in
curly brac%ets $OP( and precede it 0ith a dollar sign li%e this&
Command Target Aalue
'erifyTe3t ??di'?p
A common use of 'ariables is for storing input for an input field&
Command Target Aalue
type idGlogi
n
Selenium 'ariables can be used in either the first or second parameter and are interpreted by Selenium prior to any other operations
performed by the command& A Selenium 'ariable may also be used 0ithin a locator e3pression&
An e0ui.alent store command e%ists for each .erify and assert command- Here are a couple more commonly used store commands-
store,lementresent
This corresponds to .erify&lementPresent- It simply stores a boolean .alue)EtrueE or DfalseE)depending on #hether the 5I element is found-
storeTe3t
StoreTe%t corresponds to .erifyTe%t- It uses a locater to identify specific page te%t- The te%t+ if found+ is stored in the .ariable- StoreTe%t can
be used to e%tract te%t from the page being tested-
store,'al
This command ta'es a script as its first parameter- &mbedding :a.aScript #ithin Selenese is co.ered in the ne%t section- Store&.al allo#s the
test to store the result of running the script in a .ariable-
Da'aScript and Selenese arameters
:a.aScript can be used #ith t#o types of Selenese parameters1 script and non,script ;usually e%pressions<- In most cases+ youll #ant to
access andGor manipulate a test case .ariable inside the :a.aScript snippet used as a Selenese parameter- All .ariables created in your test
case are stored in a :a.aScript associative array- An associati.e array has string inde%es rather than se0uential numeric inde%es- The
associati.e array containing your test cases .ariables is named storedAars- Whene.er you #ish to access or manipulate a .ariable #ithin a
:a.aScript snippet+ you must refer to it as storedAarsHQyourAariableName"I-
Da'aScript @sage 0ith Script arameters
Se.eral Selenese commands specify a script parameter including assert,'al+ 'erify,'al+ store,'al+ and 0ait2or,'al- These parameters
re0uire no special synta%- A Selenium,I(& user #ould simply place a snippet of :a.aScript code into the appropriate field+ normally the
Target field ;because a script parameter is normally the first or only parameter<-
The e%ample belo# illustrates ho# a :a.aScript snippet can be used to perform a simple numerical calculation1
Command Target Aalue
store )1 hits
storeJpathCou
nt
??bloc%Nuote bloc%Nuotes
store,'al storedAarsHQ
hits"I-
storedAarsHQ
bloc%Nuotes"
I
paragraphs
This ne3t e3ample illustrates ho0 a Da'aScript snippet can include calls to methods5 in this case the Da'aScript String ob!ect"s
toJpperCase method and to,owerCase method&
Command Target Aalue
store ,dith
Wharton
name
store,'al storedAarsHQ
name"I&to@p
perCase$(
uc
store,'al storedAarsHQ
name"I&to6o
lc
Command Target Aalue
0erCase$(
Da'aScript @sage 0ith Non-Script arameters
:a.aScript can also be used to help generate .alues for parameters+ e.en #hen the parameter is not specified to be of type script- Ho#e.er+
in this case+ special synta% is re0uired)the :a.aScript snippet must be enclosed inside curly braces and preceded by the label Kaascript+
as in Kaascript D@yourCodeLere@F- Belo# is an e%ample in #hich the type commands second parameter alue is generated
.ia :a.aScript code using this special synta%1
Command Target Aalue
store league
of
nation
s
searchString
type N !a'ascriptOstor
edAarsHQsearch
String"I&to@pp
erCase$(P
echo - The Selenese rint Command
Selenese has a simple command that allo#s you to print te%t to your tests output- This is useful for pro.iding informational progress notes in
your test #hich display on the console as your test is running- These notes also can be used to pro.ide conte%t #ithin your test result reports+
#hich can be useful for finding #here a defect e%ists on a page in the e.ent your test finds a problem- $inally+ echo statements can be used to
print the contents of Selenium .ariables-
Command Target Aalue
echo Testing
page
footer
no0&

echo @sernam
e is

Alerts5 opups5 and 7ultiple Windo0s
Suppose that you are testing a page that loo's li'e this-
'
#
.
/
0
1
2
3
4
'5
''
'#
'.
'/
'0
'1
'2
'3
'4
#5
#'
##
#.
#/
#0
#1
#2
#3
#4
.5
.'
.#
..
./
.0
.1
.2
.3
<!D(CTM&- LTN,>
<html>
<head>
<script type)*te"t/Kaascript*>
!unction output(resultTe"t)D
document+get-lementOyPd(9output9)+childQodes657+nodeValue)resultTe"tR
F
!unction showScon!irm()D
ar con!irmation)con!irm(*Chose an option+*)R
i! (con!irmation))true)D
output(*Con!irmed+*)R
F
elseD
output(*IeKected!*)R
F
F
!unction showSalert()D
alert(*P9m bloc<ing!*)R
output(*:lert is gone+*)R
F
!unction showSprompt()D
ar response ) prompt(*That9s the best web U: tool;*E*$elenium*)R
output(response)R
F
!unction openSwindow(windowQame)D
window+open(*newTindow+html*EwindowQame)R
F
</script>
</head>
<body>
<input type)*button* id)*btnCon!irm* onclic<)*showScon!irm()* alue)*$how con!irm bo"* />
<input type)*button* id)*btn:lert* onclic<)*showSalert()* alue)*$how alert* />
<input type)*button* id)*btn&rompt* onclic<)*showSprompt()* alue)*$how prompt* />
<a hre!)*newTindow+html* id)*ln<QewTindow* target)*Sblan<*>Qew Tindow ,in<</a>
<input type)*button* id)*btnQewQamelessTindow* onclic<)*openSwindow()* alue)*(pen Qameless Tindow* />
.4
/5
/'
/#
/.
//
/0
<input type)*button* id)*btnQewQamedTindow* onclic<)*openSwindow(9Ni<e9)* alue)*(pen Qamed Tindow* />
<br />
<span id)*output*>
</span>
</body>
</html>
The user must respond to alertGconfirm bo%es+ as #ell as mo.ing focus to ne#ly opened popup #indo#s- $ortunately+ Selenium can co.er
:a.aScript pop,ups-
But before #e begin co.ering alertsGconfirmsGprompts in indi.idual detail+ it is helpful to understand the commonality bet#een them- Alerts+
confirmation bo%es and prompts all ha.e .ariations of the follo#ing
Command +escription
assert2oo$pattern( thro0s
error if
pattern
doesn"t
match the
te3t of the
pop-up
assert2ooresent thro0s
error if pop-
up is not
a'ailable
assert2ooNotrese
nt
thro0s
error if any
pop-up is
present
store2oo$variable( stores the
te3t of the
pop-up in a
'ariable
store2ooresent$va
riable(
stores the
te3t of the
Command +escription
pop-up in a
'ariable
and returns
true or false
When running under Selenium5 Da'aScript pop-ups 0ill not appear& This is because the function calls are actually being o'erridden
at runtime by Selenium"s o0n Da'aScript& Ho0e'er5 !ust because you cannot see the pop-up doesn"t mean you don"t ha'e to deal
0ith it& To handle a pop-up5 you must call its assert%oo(pattern) function& If you fail to assert the presence of a pop-up your
ne3t command 0ill be bloc%ed and you 0ill get an error similar to the follo0ing 6error7 -rror? There was an
une"pected Con!irmation! 6Chose an option+7
Alerts
Bets start #ith alerts because they are the simplest pop,up to handle- To begin+ open the HT*B sample abo.e in a bro#ser and clic' on the
DSho# alertE button- "oull notice that after you close the alert the te%t DAlert is gone-E is displayed on the page- No# run through the same
steps #ith Selenium I(& recording+ and .erify the te%t is added after you close the alert- "our test #ill loo' something li'e this1
Command Target Aalue
open ?
clic% btnAlert
assertAlert I"m
bloc%ing
R

'erifyTe3tresen
t
Alert is
gone&

/ou may be thin%ing BThat"s odd5 I ne'er tried to assert that alert&C But this is Selenium-I+, handling and closing the alert for you&
If you remo'e that step and replay the test you 0ill get the follo0ing error 6error7 -rror? There was an une"pected
:lert! 6P9m bloc<ing!7& /ou must include an assertion of the alert to ac%no0ledge its presence&
If you just #ant to assert that an alert is present but either dont 'no# or dont care #hat te%t it contains+ you can use
assert:lert&resent- This #ill return true or false+ #ith false halting the test-
Confirmations
!onfirmations beha.e in much the same #ay as alerts+ #ith assertCon!irmation and assertCon!irmation&resent offering
the same characteristics as their alert counterparts- Ho#e.er+ by default Selenium #ill select 6A #hen a confirmation pops up- Try recording
clic'ing on the DSho# confirm bo%E button in the sample page+ but clic' on the D!ancelE button in the popup+ then assert the output te%t-
"our test may loo' something li'e this1
Command Target Aalue
open ?
clic% btnConfir
m

chooseCancelOnNe3tConfirmati
on

assertConfirmation Choose an
option&

'erifyTe3tresent *e!ected
The chooseCancel(nQe"tCon!irmation function tells Selenium that all follo0ing confirmation should return false& It can be
reset by calling chooseO%OnNe3tConfirmation&
"ou may notice that you cannot replay this test+ because Selenium complains that there is an unhandled confirmation- This is because the
order of e.ents Selenium,I(& records causes the clic' and choose!ancel6nNe%t!onfirmation to be put in the #rong order ;it ma'es sense if
you thin' about it+ Selenium cant 'no# that youre cancelling before you open a confirmation< Simply s#itch these t#o commands and
your test #ill run fine-
+ebugging
(ebugging means finding and fi%ing errors in your test case- This is a normal part of test case de.elopment-
We #ont teach debugging here as most ne# users to Selenium #ill already ha.e some basic e%perience #ith debugging- If this is ne# to
you+ #e recommend you as' one of the de.elopers in your organi/ation-
Brea%points and Startpoints
The Sel,I(& supports the setting of brea'points and the ability to start and stop the running of a test case+ from any point #ithin the test case-
That is+ one can run up to a specific command in the middle of the test case and inspect ho# the test case beha.es at that point- To do this+ set
a brea'point on the command just before the one to be e%amined-
To set a brea'point+ select a command+ right,clic'+ and from the conte%t menu select oggle (reakpoint- Then clic' the 2un button to run
your test case from the beginning up to the brea'point-
It is also sometimes useful to run a test case from some#here in the middle to the end of the test case or up to a brea'point that follo#s the
starting point- $or e%ample+ suppose your test case first logs into the #ebsite and then performs a series of tests and you are trying to debug
one of those tests- Ho#e.er+ you only need to login once+ but you need to 'eep rerunning your tests as you are de.eloping them- "ou can
login once+ then run your test case from a startpoint placed after the login portion of your test case- That #ill pre.ent you from ha.ing to
manually logout each time you rerun your test case-
To set a startpoint+ select a command+ right,clic'+ and from the conte%t menu select "et67lear "tart &oint- Then clic' the 2un button to
e%ecute the test case beginning at that startpoint-
Stepping Through a Testcase
To e%ecute a test case one command at a time ;Dstep throughE it<+ follo# these steps1
F- Start the test case running #ith the 2un button from the toolbar-

7- Immediately pause the e%ecuting test case #ith the Pause button-

K- 2epeatedly select the Step button-

2ind Button
The $ind button is used to see #hich 5I element on the currently displayed #ebpage ;in the bro#ser< is used in the currently selected
Selenium command- This is useful #hen building a locator for a commands first parameter ;see the section on locators in the Selenium
!ommands chapter<- It can be used #ith any command that identifies a 5I element on a #ebpage+ i-e- click+ clickAnd$ait+ type+ and certain
assert and verify commands+ among others-
$rom Table .ie#+ select any command that has a locator parameter- !lic' the $ind button- No# loo' on the #ebpage1 There should be a
bright green rectangle enclosing the element specified by the locator parameter-
age Source for +ebugging
6ften+ #hen debugging a test case+ you simply must loo' at the page source ;the HT*B for the #ebpage youre trying to test< to determine a
problem- $irefo% ma'es this easy- Simply right,clic' the #ebpage and select ?3ie#,QPage Source- The HT*B opens in a separate #indo#-
5se its Search feature ;&ditTQ$ind< to search for a 'ey#ord to find the HT*B for the 5I element youre trying to test-
Alternati.ely+ select just that portion of the #ebpage for #hich you #ant to see the source- Then right,clic' the #ebpage and select 3ie#
Selection Source- In this case+ the separate HT*B #indo# #ill contain just a small amount of source+ #ith highlighting on the portion
representing your selection-
6ocator Assistance
Whene.er Selenium,I(& records a locator,type argument+ it stores additional information #hich allo#s the user to .ie# other possible
locator,type arguments that could be used instead- This feature can be .ery useful for learning more about locators+ and is often needed to
help one build a different type of locator than the type that #as recorded-
This locator assistance is presented on the Selenium,I(& #indo# as a drop,do#n list accessible at the right end of the Target field ;only
#hen the Target field contains a recorded locator,type argument<- Belo# is a snapshot sho#ing the contents of this drop,do#n for one
command- Note that the first column of the drop,do#n pro.ides alternati.e locators+ #hereas the second column indicates the type of each
alternati.e-

Writing a Test Suite
A test suite is a collection of test cases #hich is displayed in the leftmost pane in the I(&- The test suite pane can be manually opened or
closed .ia selecting a small dot half#ay do#n the right edge of the pane ;#hich is the left edge of the entire Selenium,I(& #indo# if the
pane is closed<-
The test suite pane #ill be automatically opened #hen an e%isting test suite is opened or #hen the user selects the Ne# Test !ase item from
the $ile menu- In the latter case+ the ne# test case #ill appear immediately belo# the pre.ious test case-
Selenium,I(& also supports loading pre,e%isting test cases by using the $ile ,Q Add Test !ase menu option- This allo#s you to add e%isting
test cases to a ne# test suite-
A test suite file is an HT*B file containing a one,column table- &ach cell of each ro# in the UtbodyQ section contains a lin' to a test case-
The e%ample belo# is of a test suite containing four test cases1
<html>
<head>
<meta http-e=ui)*Content-Type* content)*te"t/htmlR charset)JT%-3*>
<title>$ample $elenium Test $uite</title>
</head>
<body>
<table cellpadding)*'* cellspacing)*'* border)*'*>
<thead>
<tr><td>Test Cases !or De :nAa :-B Directory ,in<s</td></tr>
</thead>
<tbody>
<tr><td><a hre!)*+/a+html*>: ,in<s</a></td></tr>
<tr><td><a hre!)*+/b+html*>O ,in<s</a></td></tr>
<tr><td><a hre!)*+/c+html*>C ,in<s</a></td></tr>
<tr><td><a hre!)*+/d+html*>D ,in<s</a></td></tr>
</tbody>
</table>
</body>
</html>
Note
Test case files should not ha.e to be co,located #ith the test suite file that in.o'es them- And on *ac 6S and Binu% systems+ that is indeed
the case- Ho#e.er+ at the time of this #riting+ a bug pre.ents Windo#s users from being able to place the test cases else#here than #ith the
test suite that in.o'es them-
@ser ,3tensions
5ser e%tensions are :a.aScript files that allo# one to create his or her o#n customi/ations and features to add additional functionality- 6ften
this is in the form of customi/ed commands although this e%tensibility is not limited to additional commands-
There are a number of useful e%tensions created by users-
4.&-*AN: H4" "'74-N 4" -) -1 #A'8$' $4++ (' *'54"4N9 H4" "--N.
Perhaps the most popular of all Selenium,I(& e%tensions is one #hich pro.ides flo# control in the form of #hile loops and primiti.e
conditionals- This e%tension is the goto\sel\ide-js- $or an e%ample of ho# to use the functionality pro.ided by this e%tension+ loo' at the
page created by its author-
To install this e%tension+ put the pathname to its location on your computer in the Selenium Core e3tensions field of Selenium,I(&s
6ptionsTQ6ptionsTQ>eneral tab-

After selecting the OS button+ you must close and reopen Selenium,I(& in order for the e%tensions file to be read- Any change you ma'e to
an e%tension #ill also re0uire you to close and reopen Selenium,I(&-
Information on #riting your o#n e%tensions can be found near the bottom of the Selenium 2eference document-
2ormat
$ormat+ under the 6ptions menu+ allo#s you to select a language for sa.ing and displaying the test case- The default is HT*B-
If you #ill be using Selenium,2! to run your test cases+ this feature is used to translate your test case into a programming language- Select
the language+ e-g- :a.a+ PHP+ you #ill be using #ith Selenium,2! for de.eloping your test programs- Then simply sa.e the test case using
$ileTQ&%port Test !ase As- "our test case #ill be translated into a series of functions in the language you choose- &ssentially+ program code
supporting your test is generated for you by Selenium,I(&-
Also+ note that if the generated code does not suit your needs+ you can alter it by editing a configuration file #hich defines the generation
process- &ach supported language has configuration settings #hich are editable- This is under the 6ptionsTQ6ptionsTQ$ormats tab-
Note
At the time of this #riting+ this feature is not yet supported by the Selenium de.elopers- Ho#e.er the author has altered the !H format in a
limited manner and it has #or'ed #ell-
,3ecuting Selenium-I+, Tests on +ifferent Bro0sers
While Selenium,I(& can only run tests against $irefo%+ tests de.eloped #ith Selenium,I(& can be run against other bro#sers+ using a
simple command,line interface that in.o'es the Selenium,2! ser.er- This topic is co.ered in the 2un Selenese tests section on Selenium,2!
chapter- The :html"uite command,line option is the particular feature of interest-
Troubleshooting
Belo# is a list of imageGe%planation pairs #hich describe fre0uent sources of problems #ith Selenium,I(&1
able view is not available with this format.
This message can be occasionally displayed in the Table tab #hen Selenium I(& is launched- The #or'around is to close and reopen
Selenium I(&- See issue F88@- for more information- If you are able to reproduce this reliably then please pro.ide details so that #e can
#or' on a fi%-
error loading test case: no command found
"ou.e used 2ileGFOpen to try to open a test suite file- 5se 2ileGFOpen Test Suite instead-
An enhancement re0uest has been raised to impro.e this error message- See issue F8F8-

This type of error may indicate a timing problem+ i-e-+ the element specified by a locator in your command #asnt fully loaded #hen the
command #as e%ecuted- Try putting a pause T111 before the command to determine #hether the problem is indeed related to timing- If so+
in.estigate using an appropriate 0ait2or9 or 9AndWait command before the failing command-

Whene.er your attempt to use .ariable substitution fails as is the case for the open command abo.e+ it indicates that you ha.ent actually
created the .ariable #hose .alue youre trying to access- This is sometimes due to putting the .ariable in the Aalue field #hen it should be in
the Target field or .ice .ersa- In the e%ample abo.e+ the t#o parameters for the store command ha.e been erroneously placed in the re.erse
order of #hat is re0uired- $or any Selenese command+ the first re0uired parameter must go in the Target field+ and the second re0uired
parameter ;if one e%ists< must go in the Aalue field-
error loading test case: ;'%ception... <7omponent returned failure code: =%>=?2==@2 /N"A'**-*A14+'AN-A1-)N#0
;ns41ile4nput"tream.initBC nresult: <=%>=?2==@2 /N"A'**-*A14+'AN-A1-)N#0C location: <D" frame :: chrome:66selenium:
ide6content6file:utils.Es :: anonymous :: line F>C data: noB
6ne of the test cases in your test suite cannot be found- *a'e sure that the test case is indeed located #here the test suite indicates it is
located- Also+ ma'e sure that your actual test case files ha.e the -html e%tension both in their filenames+ and in the test suite file #here they
are referenced-
An enhancement re0uest has been raised to impro.e this error message- See issue F8FF-

"our e%tension files contents ha.e not been read by Selenium,I(&- Be sure you ha.e specified the proper pathname to the e%tensions file
.ia OptionsGFOptionsGF.eneral in the Selenium Core e3tensions field- Also+ Selenium,I(& must be restarted after any change to either
an e%tensions file or to the contents of the Selenium Core e3tensions field-
Na'igation
Selenium (ocumentation ^
ne%t
pre.ious Y
Table Of Contents
Selenium Web(ri.er
Introducing Web(ri.er
Ho# (oes Web(ri.er ?(ri.e the Bro#ser !ompared to Selenium,2!?
Web(ri.er and the Selenium,Ser.er
Setting 5p a Selenium,Web(ri.er Project
*igrating from Selenium F-8
Introducing the Selenium,Web(ri.er API by &%ample
Selenium,Web(ri.er API !ommands and 6perations
(ri.er Specifics and Tradeoffs
Selenium,Web(ri.ers (ri.ers
Alternati.e Bac',&nds1 *i%ing Web(ri.er and 2! Technologies
2unning Standalone Selenium Ser.er for use #ith 2emote(ri.ers
Additional 2esources
Ne%t Steps
Selenium Web+ri'er
N-': $e3re currently working on documenting these sections. $e believe the information here is accurate, however be aware we are also
still working on this chapter. Additional information will be provided as we go which should make this chapter more solid.
Introducing Web+ri'er
The primary ne# feature in Selenium 7-8 is the integration of the Web(ri.er API- Web(ri.er is designed to pro.ide a simpler+ more concise
programming interface in addition to addressing some limitations in the Selenium,2! API- Selenium,Web(ri.er #as de.eloped to better
support dynamic #eb pages #here elements of a page may change #ithout the page itself being reloaded- Web(ri.ers goal is to supply a
#ell,designed object,oriented API that pro.ides impro.ed support for modern ad.anced #eb,app testing problems-
Ho0 +oes Web+ri'er Q+ri'e" the Bro0ser Compared to Selenium-*C?
Selenium,Web(ri.er ma'es direct calls to the bro#ser using each bro#sers nati.e support for automation- Ho# these direct calls are made+
and the features they support depends on the bro#ser you are using- Information on each ?bro#ser dri.er is pro.ided later in this chapter-
$or those familiar #ith Selenium,2!+ this is 0uite different from #hat you are used to- Selenium,2! #or'ed the same #ay for each
supported bro#ser- It ?injected ja.ascript functions into the bro#ser #hen the bro#ser #as loaded and then used its ja.ascript to dri.e the
A5T #ithin the bro#ser- Web(ri.er does not use this techni0ue- Again+ it dri.es the bro#ser directly using the bro#sers built in support for
automation-
Web+ri'er and the Selenium-Ser'er
"ou may+ or may not+ need the Selenium Ser.er+ depending on ho# you intend to use Selenium,Web(ri.er- If you #ill be only using the
Web(ri.er API you do not need the Selenium,Ser.er- If your bro#ser and tests #ill all run on the same machine+ and your tests only use the
Web(ri.er API+ then you do not need to run the Selenium,Ser.erP Web(ri.er #ill run the bro#ser directly-
There are some reasons though to use the Selenium,Ser.er #ith Selenium,Web(ri.er-
"ou are using Selenium,>rid to distribute your tests o.er multiple machines or .irtual machines ;3*s<-
"ou #ant to connect to a remote machine that has a particular bro#ser .ersion that is not on your current machine-
"ou are not using the :a.a bindings ;i-e- Python+ !H+ or 2uby< and #ould li'e to use Html5nit (ri.er
Setting @p a Selenium-Web+ri'er ro!ect
To install Selenium means to set up a project in a de.elopment so you can #rite a program using Selenium- Ho# you do this depends on
your programming language and your de.elopment en.ironment-
Da'a
The easiest #ay to set up a Selenium 7-8 :a.a project is to use *a.en- *a.en #ill do#nload the ja.a bindings ;the Selenium 7-8 ja.a client
library< and all its dependencies+ and #ill create the project for you+ using a ma.en pom-%ml ;project configuration< file- 6nce you.e done
this+ you can import the ma.en project into your preferred I(&+ Intelli: I(&A or &clipse-
$irst+ create a folder to contain your Selenium project files- Then+ to use *a.en+ you need a pom-%ml file- This can be created #ith a te%t
editor- We #ont teach the details of pom-%ml files or for using *a.en since there are already e%cellent references on this- "our pom-%ml file
#ill loo' something li'e this- !reate this file in the folder you created for your project-
<;"ml ersion)*'+5* encoding)*JT%-3*;>
<proKect "mlns)*http?//maen+apache+org/&(N//+5+5*
"mlns?"si)*http?//www+w.+org/#55'/VN,$chema-instance*
"si?schema,ocation)*http?//maen+apache+org/&(N//+5+5 http?//maen+apache+org/"sd/maen-
/+5+5+"sd*>
<modelVersion>/+5+5</modelVersion>
<groupPd>Ny$el#5&roK</groupPd>
<arti!actPd>Ny$el#5&roK</arti!actPd>
<ersion>'+5</ersion>
<dependencies>
<dependency>
<groupPd>org+seleniumh=+selenium</groupPd>
<arti!actPd>selenium-Kaa</arti!actPd>
<ersion>#+./+5</ersion>
</dependency>
<dependency>
<groupPd>com+opera</groupPd>
<arti!actPd>operadrier</arti!actPd>
</dependency>
</dependencies>
<dependencyNanagement>
<dependencies>
<dependency>
<groupPd>com+opera</groupPd>
<arti!actPd>operadrier</arti!actPd>
<ersion>'+.</ersion>
<e"clusions>
<e"clusion>
<groupPd>org+seleniumh=+selenium</groupPd>
<arti!actPd>selenium-remote-drier</arti!actPd>
</e"clusion>
</e"clusions>
</dependency>
</dependencies>
</dependencyNanagement>
</proKect>
Be sure you specify the most current .ersion- At the time of #riting+ the .ersion listed abo.e #as the most current+ ho#e.er there #ere
fre0uent releases immediately after the release of Selenium 7-8- !hec' the *a.en do#nload page for the current release and edit the abo.e
dependency accordingly-
No#+ from a command,line+ !( into the project directory and run ma.en as follo#s-
mn clean install
This #ill do#nload Selenium and all its dependencies and #ill add them to the project-
$inally+ import the project into your preferred de.elopment en.ironment- $or those not familiar #ith this+ #e.e pro.ided an appendi% #hich
sho#s this-
Importing a ma.en project into Intelli: I(&A- Importing a ma.en project into &clipse-
CU
As of Selenium 7-7-8+ the !H bindings are distributed as a set of signed dlls along #ith other dependency dlls- Prior to 7-7-8+ all Selenium
dlls #ere unsigned- To include Selenium in your project+ simply do#nload the latest selenium,dotnet /ip file from
https1GGcode-google-comGpGseleniumGdo#nloadsGlist- If you are using Windo#s 3ista or abo.e+ you should unbloc' the /ip file before
un/ipping it1 2ight clic' on the /ip file+ clic' DPropertiesE+ clic' D5nbloc'E and clic' D6AE-
5n/ip the contents of the /ip file+ and add a reference to each of the un/ipped dlls to your project in 3isual Studio ;or your I(& of choice<-
6fficial Nu>et Pac'ages1 2! Web(ri.er Web(ri.erBac'edSelenium Support
ython
If you are using Python for test automation then you probably are already familiar #ith de.eloping in Python- To add Selenium to your
Python en.ironment run the follo#ing command from a command,line-
pip install selenium
Pip re0uires pip to be installed+ pip also has a dependency on setuptools-
Teaching Python de.elopment itself is beyond the scope of this document+ ho#e.er there are many resources on Python and li'ely
de.elopers in your organi/ation can help you get up to speed-
*uby
If you are using 2uby for test automation then you probably are already familiar #ith de.eloping in 2uby- To add Selenium to your 2uby
en.ironment run the follo#ing command from a command,line-
gem install selenium-webdrier
Teaching 2uby de.elopment itself is beyond the scope of this document+ ho#e.er there are many resources on 2uby and li'ely de.elopers in
your organi/ation can help you get up to speed-
erl
Perl bindings are pro.ided by a third party+ please refer to any of their documentation on ho# to install G get started- There is one 'no#n Perl
binding as of this #riting-
H
PHP bindings are pro.ided by a third party+ please refer to any of their documentation on ho# to install G get started- There are three 'no#n
bindings at this time1 By !hibimagic By Bu'as/ Aolc/yns'i and By the $aceboo'
7igrating from Selenium )&1
$or those #ho already ha.e test suites #ritten using Selenium F-8+ #e ha.e pro.ided tips on ho# to migrate your e%isting code to Selenium
7-8- Simon Ste#art+ the lead de.eloper for Selenium 7-8+ has #ritten an article on migrating from Selenium F-8- We.e included this as an
appendi%-
*igrating $rom Selenium 2! to Selenium Web(ri.er
Introducing the Selenium-Web+ri'er AI by ,3ample
Web(ri.er is a tool for automating #eb application testing+ and in particular to .erify that they #or' as e%pected- It aims to pro.ide a
friendly API thats easy to e%plore and understand+ easier to use than the Selenium,2! ;F-8< API+ #hich #ill help to ma'e your tests easier to
read and maintain- Its not tied to any particular test frame#or'+ so it can be used e0ually #ell in a unit testing or from a plain old DmainE
method- This section introduces Web(ri.ers API and helps get you started becoming familiar #ith it- Start by setting up a Web(ri.er
project if you ha.ent already- This #as described in the pre.ious section+ Setting 5p a Selenium,Web(ri.er Project-
6nce your project is set up+ you can see that Web(ri.er acts just as any normal library1 it is entirely self,contained+ and you usually dont
need to remember to start any additional processes or run any installers before using it+ as opposed to the pro%y ser.er #ith Selenium,2!-
Note1 additional steps are re0uired to use !hrome (ri.er+ 6pera (ri.er+ Android (ri.er and iPhone (ri.er
"oure no# ready to #rite some code- An easy #ay to get started is this e%ample+ #hich searches for the term D!heeseE on >oogle and then
outputs the result pages title to the console-
pac<age org+open=a+selenium+e"ampleR
import org+open=a+selenium+OyR
import org+open=a+selenium+TebDrierR
import org+open=a+selenium+Teb-lementR
import org+open=a+selenium+!ire!o"+%ire!o"DrierR
import org+open=a+selenium+support+ui+-"pectedConditionR
import org+open=a+selenium+support+ui+TebDrierTaitR
public class $elenium#-"ample D
public static oid main($tring67 args) D
// Create a new instance o! the %ire!o" drier
// Qotice that the remainder o! the code relies on the inter!aceE
// not the implementation+
TebDrier drier ) new %ire!o"Drier()R
// :nd now use this to isit Woogle
drier+get(*http?//www+google+com*)R
// :lternatiely the same thing can be done li<e this
// drier+naigate()+to(*http?//www+google+com*)R
// %ind the te"t input element by its name
Teb-lement element ) drier+!ind-lement(Oy+name(*=*))R
// -nter something to search !or
element+sendXeys(*Cheese!*)R
// Qow submit the !orm+ TebDrier will !ind the !orm !or us !rom the element
element+submit()R
// Chec< the title o! the page
$ystem+out+println(*&age title is? * C drier+getTitle())R

// Woogle9s search is rendered dynamically with Yaa$cript+
// Tait !or the page to loadE timeout a!ter '5 seconds
(new TebDrierTait(drierE '5))+until(new -"pectedCondition<Ooolean>() D
public Ooolean apply(TebDrier d) D
return d+getTitle()+to,owerCase()+startsTith(*cheese!*)R
F
F)R
// $hould see? *cheese! - Woogle $earch*
$ystem+out+println(*&age title is? * C drier+getTitle())R

//Close the browser
drier+=uit()R
F
F
In upcoming sections+ you #ill learn more about ho# to use Web(ri.er for things such as na.igating for#ard and bac'#ard in your
bro#sers history+ and ho# to test #eb sites that use frames and #indo#s- We also pro.ide a more thorough discussions and e%amples-
Selenium-Web+ri'er AI Commands and Operations
2etching a age
The first thing youre li'ely to #ant to do #ith Web(ri.er is na.igate to a page- The normal #ay to do this is by calling DgetE1
drier+get(*http?//www+google+com*)R
(ependent on se.eral factors+ including the 6SGBro#ser combination+ Web(ri.er may or may not #ait for the page to load- In some
circumstances+ Web(ri.er may return control before the page has finished+ or e.en started+ loading- To ensure robustness+ you need to #ait
for the element;s< to e%ist in the page using &%plicit and Implicit Waits-
6ocating @I ,lements $Web,lements(
Bocating elements in Web(ri.er can be done on the Web(ri.er instance itself or on a Web&lement- &ach of the language bindings e%pose a
D$ind &lementE and D$ind &lementsE method- The first returns a Web&lement object other#ise it thro#s an e%ception- The latter returns a
list of Web&lements+ it can return an empty list if no (6* elements match the 0uery-
The D$indE methods ta'e a locator or 0uery object called DByE- DByE strategies are listed belo#-
By I+
This is the most efficient and preferred #ay to locate an element- !ommon pitfalls that 5I de.elopers ma'e is ha.ing non,uni0ue ids on a
page or auto,generating the id+ both should be a.oided- A class on an html element is more appropriate than an auto,generated id-
&%ample of ho# to find an element that loo's li'e this1
<di id)*coolestTidget-ah*>+++</di>
Teb-lement element ) drier+!ind-lement(Oy+id(*coolestTidget-ah*))R
By Class Name
D!lassE in this case refers to the attribute on the (6* element- 6ften in practical use there are many (6* elements #ith the same class
name+ thus finding multiple elements becomes the more practical option o.er finding the first element-
&%ample of ho# to find an element that loo's li'e this1
<di class)*cheese*><span>Cheddar</span></di><di class)*cheese*><span>Wouda</span></di>
,ist<Teb-lement> cheeses ) drier+!ind-lements(Oy+classQame(*cheese*))R
By Tag Name
The (6* Tag Name of the element-
&%ample of ho# to find an element that loo's li'e this1
<i!rame src)*+++*></i!rame>
Teb-lement !rame ) drier+!ind-lement(Oy+tagQame(*i!rame*))R
By Name
$ind the input element #ith matching name attribute-
&%ample of ho# to find an element that loo's li'e this1
<input name)*cheese* type)*te"t*/>
Teb-lement cheese ) drier+!ind-lement(Oy+name(*cheese*))R
By 6in% Te3t
$ind the lin' element #ith matching .isible te%t-
&%ample of ho# to find an element that loo's li'e this1
<a hre!)*http?//www+google+com/search;=)cheese*>cheese</a>>
Teb-lement cheese ) drier+!ind-lement(Oy+lin<Te"t(*cheese*))R
By artial 6in% Te3t
$ind the lin' element #ith partial matching .isible te%t-
&%ample of ho# to find an element that loo's li'e this1
<a hre!)*http?//www+google+com/search;=)cheese*>search !or cheese</a>>
Teb-lement cheese ) drier+!ind-lement(Oy+partial,in<Te"t(*cheese*))R
By CSS
Bi'e the name implies it is a locator strategy by css- Nati.e bro#ser support is used by default+ so please refer to w3c css selectors
Ghttp:66www.w3.org6*67""6HselectorsI for a list of generally a.ailable css selectors- If a bro#ser does not ha.e nati.e support for css
0ueries+ then Si//le is used- I& =+I and $$K-8 currently use Si//le as the css 0uery engine-
Be#are that not all bro#sers #ere created e0ual+ some css that might #or' in one .ersion may not #or' in another-
&%ample of to find the cheese belo#1
<di id)*!ood*><span class)*dairy*>mil<</span><span class)*dairy aged*>cheese</span></di>
Teb-lement cheese ) drier+!ind-lement(Oy+css$elector(*>!ood span+dairy+aged*))R
By JATH
At a high le.el+ Web(ri.er uses a bro#sers nati.e OPath capabilities #here.er possible- 6n those bro#sers that dont ha.e nati.e OPath
support+ #e ha.e pro.ided our o#n implementation- This can lead to some une%pected beha.iour unless you are a#are of the differences in
the .arious %path engines-
+ri'er
Tag and
Attribute
Name
Attribute
Aalues
Nati'e
Jath
Support
Html5nit
(ri.er
Bo#er,cased As they
appear in
the
HT*B
"es
Internet
&%plorer
(ri.er
Bo#er,cased As they
appear in
the
HT*B
No
$irefo%
(ri.er
!ase
insensiti.e
As they
appear in
the
HT*B
"es
This is a little abstract+ so for the follo#ing piece of HT*B1
<input type)*te"t* name)*e"ample* />
<PQ&JT type)*te"t* name)*other* />
,ist<Teb-lement> inputs ) drier+!ind-lements(Oy+"path(*//input*))R
The follo#ing number of matches #ill be found
Jath
e3pression
Html@nit
+ri'er
2irefo3
+ri'er
Internet
,3plorer
+ri'er
GGinput F 7 7
Jath
e3pression
Html@nit
+ri'er
2irefo3
+ri'er
Internet
,3plorer
+ri'er
;De%ample
E<
GGINP5T 8 7 8
Sometimes HT*B elements do not need attributes to be e%plicitly declared because they #ill default to 'no#n .alues- $or e%ample+ the
DinputE tag does not re0uire the DtypeE attribute because it defaults to Dte%tE- The rule of thumb #hen using %path in Web(ri.er is that you
should not e%pect to be able to match against these implicit attributes-
@sing Da'aScript
"ou can e%ecute arbitrary ja.ascript to find an element and as long as you return a (6* &lement+ it #ill be automatically con.erted to a
Web&lement object-
Simple e%ample on a page that has j4uery loaded1
Teb-lement element ) (Teb-lement) ((Yaascript-"ecutor)drier)+e"ecute$cript(*return Z(9+cheese9)657*)R
$inding all the input elements to the e.ery label on a page1
,ist<Teb-lement> labels ) drier+!ind-lements(Oy+tagQame(*label*))R
,ist<Teb-lement> inputs ) (,ist<Teb-lement>) ((Yaascript-"ecutor)drier)+e"ecute$cript(
*ar labels ) arguments657E inputs ) 67R !or (ar i)5R i < labels+lengthR iCC)D* C
*inputs+push(document+get-lementOyPd(labels6i7+get:ttribute(9!or9)))R F return inputsR*E labels)R
@ser Input - 2illing In 2orms
We.e already seen ho# to enter te%t into a te%tarea or te%t field+ but #hat about the other elements? "ou can DtoggleE the state of
chec'bo%es+ and you can use Dclic'E to set something li'e an 6PTI6N tag selected- (ealing #ith S&B&!T tags isnt too bad1
Teb-lement select ) drier+!ind-lement(Oy+tagQame(*select*))R
,ist<Teb-lement> all(ptions ) select+!ind-lements(Oy+tagQame(*option*))R
!or (Teb-lement option ? all(ptions) D
$ystem+out+println($tring+!ormat(*Value is? [s*E option+get:ttribute(*alue*)))R
option+clic<()R
F
This #ill find the first DS&B&!TE element on the page+ and cycle through each of its 6PTI6Ns in turn+ printing out their .alues+ and
selecting each in turn- As you #ill notice+ this isnt the most efficient #ay of dealing #ith S&B&!T elements- Web(ri.ers support classes
include one called DSelectE+ #hich pro.ides useful methods for interacting #ith these-
$elect select ) new $elect(drier+!ind-lement(Oy+tagQame(*select*)))R
select+deselect:ll()R
select+selectOyVisibleTe"t(*-dam*)R
This #ill deselect all 6PTI6Ns from the first S&B&!T on the page+ and then select the 6PTI6N #ith the displayed te%t of D&damE-
6nce you.e finished filling out the form+ you probably #ant to submit it- 6ne #ay to do this #ould be to find the DsubmitE button and clic'
it1
drier+!ind-lement(Oy+id(*submit*))+clic<()R
Alternati.ely+ Web(ri.er has the con.enience method DsubmitE on e.ery element- If you call this on an element #ithin a form+ Web(ri.er
#ill #al' up the (6* until it finds the enclosing form and then calls submit on that- If the element isnt in a form+ then the
Qo$uch-lement-"ception #ill be thro#n1
element+submit()R
7o'ing Bet0een Windo0s and 2rames
Some #eb applications ha.e many frames or multiple #indo#s- Web(ri.er supports mo.ing bet#een named #indo#s using the Ds#itchToE
method1
drier+switchTo()+window(*windowQame*)R
All calls to drier #ill no# be interpreted as being directed to the particular #indo#- But ho# do you 'no# the #indo#s name? Ta'e a
loo' at the ja.ascript or lin' that opened it1
<a hre!)*somewhere+html* target)*windowQame*>Clic< here to open a new window</a>
Alternati.ely+ you can pass a D#indo# handleE to the Ds#itchTo;<-#indo#;<E method- Ano#ing this+ its possible to iterate o.er e.ery open
#indo# li'e so1
!or ($tring handle ? drier+getTindowLandles()) D
drier+switchTo()+window(handle)R
F
"ou can also s#itch from frame to frame ;or into iframes<1
drier+switchTo()+!rame(*!rameQame*)R
Its possible to access subframes by separating the path #ith a dot+ and you can specify the frame by its inde% too- That is1
drier+switchTo()+!rame(*!rameQame+5+child*)R
#ould go to the frame named DchildE of the first subframe of the frame called DframeNameE- All frames are e'aluated as if from 9top9&
opup +ialogs
Starting #ith Selenium 7-8 beta F+ there is built in support for handling popup dialog bo%es- After you.e triggered an action that opens a
popup+ you can access the alert #ith the follo#ing1
:lert alert ) drier+switchTo()+alert()R
This #ill return the currently open alert object- With this object you can no# accept+ dismiss+ read its contents or e.en type into a prompt-
This interface #or's e0ually #ell on alerts+ confirms+ and prompts- 2efer to the :a.a(ocs or 2uby(ocs for more information-
Na'igationK History and 6ocation
&arlier+ #e co.ered na.igating to a page using the DgetE command ; drier+get(*http?//www+e"ample+com*)< As you.e seen+
Web(ri.er has a number of smaller+ tas',focused interfaces+ and na.igation is a useful tas'- Because loading a page is such a fundamental
re0uirement+ the method to do this li.es on the main Web(ri.er interface+ but its simply a synonym to1
drier+naigate()+to(*http?//www+e"ample+com*)R
To reiterate1 Dnaigate()+to()E and Dget()E do e%actly the same thing- 6nes just a lot easier to type than the otherZ
The Dna.igateE interface also e%poses the ability to mo.e bac'#ards and for#ards in your bro#sers history1
drier+naigate()+!orward()R
drier+naigate()+bac<()R
Please be a#are that this functionality depends entirely on the underlying bro#ser- Its just possible that something une%pected may happen
#hen you call these methods if youre used to the beha.iour of one bro#ser o.er another-
Coo%ies
Before #e lea.e these ne%t steps+ you may be interested in understanding ho# to use coo'ies- $irst of all+ you need to be on the domain that
the coo'ie #ill be .alid for- If you are trying to preset coo'ies before you start interacting #ith a site and your homepage is large G ta'es a
#hile to load an alternati.e is to find a smaller page on the site+ typically the 989 page is small ;http1GGe%ample-comGsome989page<
// Wo to the correct domain
drier+get(*http?//www+e"ample+com*)R
// Qow set the coo<ie+ This one9s alid !or the entire domain
Coo<ie coo<ie ) new Coo<ie(*<ey*E *alue*)R
drier+manage()+addCoo<ie(coo<ie)R
// :nd now output all the aailable coo<ies !or the current JI,
$et<Coo<ie> allCoo<ies ) drier+manage()+getCoo<ies()R
!or (Coo<ie loadedCoo<ie ? allCoo<ies) D
$ystem+out+println($tring+!ormat(*[s -> [s*E loadedCoo<ie+getQame()E loadedCoo<ie+getValue()))R
F
// Mou can delete coo<ies in . ways
// Oy name
drier+manage()+deleteCoo<ieQamed(*Coo<ieQame*)R
// Oy Coo<ie
drier+manage()+deleteCoo<ie(loadedCoo<ie)R
// (r all o! them
drier+manage()+delete:llCoo<ies()R
Changing the @ser Agent
This is easy #ith the $irefo% (ri.er1
%ire!o"&ro!ile pro!ile ) new %ire!o"&ro!ile()R
pro!ile+add:dditional&re!erence(*general+useragent+oerride*E *some J: string*)R
TebDrier drier ) new %ire!o"Drier(pro!ile)R
+rag And +rop
Heres an e%ample of using the Actions class to perform a drag and drop- Nati.e e.ents are re0uired to be enabled-
Teb-lement element ) drier+!ind-lement(Oy+name(*source*))R
Teb-lement target ) drier+!ind-lement(Oy+name(*target*))R
(new :ctions(drier))+drag:ndDrop(elementE target)+per!orm()R
+ri'er Specifics and Tradeoffs
Selenium-Web+ri'er"s +ri'ers
Web(ri.er is the name of the 'ey interface against #hich tests should be #ritten+ but there are se.eral implementations- These include1
Html@nit +ri'er
This is currently the fastest and most light#eight implementation of Web(ri.er- As the name suggests+ this is based on Html5nit- Html5nit
is a ja.a based implementation of a WebBro#ser #ithout a >5I- $or any language binding ;other than ja.a< the Selenium Ser.er is re0uired
to use this dri.er-
@sage
TebDrier drier ) new LtmlJnitDrier()R
ros
$astest implementation of Web(ri.er
A pure :a.a solution and so it is platform independent-
Supports :a.aScript
Cons
&mulates other bro#sers :a.aScript beha.iour ;see belo#<
Da'aScript in the Html@nit +ri'er
None of the popular bro#sers uses the :a.aScript engine used by Html5nit ;2hino<- If you test :a.aScript using Html5nit the results may
differ significantly from those bro#sers-
When #e say D:a.aScriptE #e actually mean D:a.aScript and the (6*E- Although the (6* is defined by the WK! each bro#ser has its
o#n 0uir's and differences in their implementation of the (6* and in ho# :a.aScript interacts #ith it- Html5nit has an impressi.ely
complete implementation of the (6* and has good support for using :a.aScript+ but it is no different from any other bro#ser1 it has its o#n
0uir's and differences from both the WK! standard and the (6* implementations of the major bro#sers+ despite its ability to mimic other
bro#sers-
With Web(ri.er+ #e had to ma'e a choiceP do #e enable Html5nits :a.aScript capabilities and run the ris' of teams running into problems
that only manifest themsel.es there+ or do #e lea.e :a.aScript disabled+ 'no#ing that there are more and more sites that rely on :a.aScript?
We too' the conser.ati.e approach+ and by default ha.e disabled support #hen #e use Html5nit- With each release of both Web(ri.er and
Html5nit+ #e reassess this decision1 #e hope to enable :a.aScript by default on the Html5nit at some point-
,nabling Da'aScript
If you cant #ait+ enabling :a.aScript support is .ery easy1
LtmlJnitDrier drier ) new LtmlJnitDrier(true)R
This #ill cause the Html5nit (ri.er to emulate $irefo% K-=s :a.aScript handling by default-
2irefo3 +ri'er
!ontrols the $irefo% bro#ser using a $irefo% plugin- The $irefo% Profile that is used is stripped do#n from #hat is installed on the machine
to only include the Selenium Web(ri.er-%pi ;plugin<- A fe# settings are also changed by default ;see the source to see #hich ones< $irefo%
(ri.er is capable of being run and is tested on Windo#s+ *ac+ Binu%- !urrently on .ersions K-=+ F8+ latest , F+ latest
@sage
TebDrier drier ) new %ire!o"Drier()R
ros
2uns in a real bro#ser and supports :a.aScript
$aster than the Internet &%plorer (ri.er
Cons
Slo#er than the Html5nit (ri.er
7odifying the 2irefo3 rofile
Suppose that you #anted to modify the user agent string ;as abo.e<+ but you.e got a tric'ed out $irefo% profile that contains do/ens of
useful e%tensions- There are t#o #ays to obtain this profile- Assuming that the profile has been created using $irefo%s profile manager
;!ire!o" -&ro!ileNanager<1
&ro!ilesPni all&ro!iles ) new &ro!ilesPni()R
%ire!o"&ro!ile pro!ile ) all&ro!iles+get&ro!ile(*TebDrier*)R
pro!ile+set&re!erences(*!oo+bar*E #.)R
TebDrier drier ) new %ire!o"Drier(pro!ile)R
Alternati.ely+ if the profile isnt already registered #ith $irefo%1
%ile pro!ileDir ) new %ile(*path/to/top/leel/o!/pro!ile*)R
%ire!o"&ro!ile pro!ile ) new %ire!o"&ro!ile(pro!ileDir)R
pro!ile+add:dditional&re!erences(e"tra&re!s)R
TebDrier drier ) new %ire!o"Drier(pro!ile)R
As #e de.elop features in the $irefo% (ri.er+ #e e%pose the ability to use them- $or e%ample+ until #e feel nati.e e.ents are stable on
$irefo% for Binu%+ they are disabled by default- To enable them1
%ire!o"&ro!ile pro!ile ) new %ire!o"&ro!ile()R
pro!ile+set-nableQatie-ents(true)R
TebDrier drier ) new %ire!o"Drier(pro!ile)R
Info
See the $irefo% section in the #i'i page for the most up to date info-
Internet ,3plorer +ri'er
This dri.er is controlled by a -dll and is thus only a.ailable on Windo#s 6S- &ach Selenium release has its core functionality tested against
.ersions =+ I and @ on OP+ and C on Windo#sI-
@sage
TebDrier drier ) new Pnternet-"plorerDrier()R
ros
2uns in a real bro#ser and supports :a.aScript #ith all the 0uir's your end users see-
Cons
6b.iously the Internet &%plorer (ri.er #ill only #or' on Windo#sZ
!omparati.ely slo# ;though still pretty snappy 1<
OPath is not nati.ely supported in most .ersions- Si//le is injected automatically #hich is significantly slo#er than other bro#sers
and slo#er #hen comparing to !SS selectors in the same bro#ser-
!SS is not nati.ely supported in .ersions = and I- Si//le is injected instead-
!SS selectors in I& @ and C are nati.e+ but those bro#sers dont fully support !SSK
Info
See the Internet &%plorer section of the #i'i page for the most up to date info- Please ta'e special note of the 2e0uired !onfiguration
section-
Chrome +ri'er
!hrome (ri.er is maintained G supported by the !hromium project iteslf- Web(ri.er #or's #ith !hrome through the chromedri.er binary
;found on the chromium projects do#nload page<- "ou need to ha.e both chromedri.er and a .ersion of chrome bro#ser installed-
chromedri.er needs to be placed some#here on your systems path in order for Web(ri.er to automatically disco.er it- The !hrome bro#ser
itself is disco.ered by chromedri.er in the default installation path- These both can be o.erridden by en.ironment .ariables- Please refer to
the #i'i for more information-
@sage
TebDrier drier ) new ChromeDrier()R
ros
2uns in a real bro#ser and supports :a.aScript
Because !hrome is a Web'it,based bro#ser+ the !hrome (ri.er may allo# you to .erify that your site #or's in Safari- Note that
since !hrome uses its o#n 3@ :a.aScript engine rather than Safaris Nitro engine+ :a.aScript e%ecution may differ-
Cons
Slo#er than the Html5nit (ri.er
Info
See our #i'i for the most up to date info- *ore info can also be found on the do#nloads page
.etting running 0ith Chrome +ri'er
(o#nload the !hrome (ri.er e%ecutable and follo# the other instructions on the #i'i page
Opera +ri'er
See the 6pera (ri.er #i'i article in the Selenium Wi'i for information on using the 6pera (ri.er-
ihone +ri'er
See the iPhone (ri.er #i'i article in the Selenium Wi'i for information on using the *ac i6S (ri.er-
Android +ri'er
See the Android (ri.er #i'i article in the Selenium Wi'i for information on using the Android (ri.er-
Alternati'e Bac%-,ndsK 7i3ing Web+ri'er and *C Technologies
Web+ri'er-Bac%ed Selenium-*C
The :a.a .ersion of Web(ri.er pro.ides an implementation of the Selenium,2! API- These means that you can use the underlying
Web(ri.er technology using the Selenium,2! API- This is primarily pro.ided for bac'#ards compatibility- It allo#s those #ho ha.e
e%isting test suites using the Selenium,2! API to use Web(ri.er under the co.ers- Its pro.ided to help ease the migration path to Selenium,
Web(ri.er- Also+ this allo#s one to use both APIs+ side,by,side+ in the same test code-
Selenium,Web(ri.er is used li'e this1
// Mou may use any TebDrier implementation+ %ire!o" is used here as an e"ample
TebDrier drier ) new %ire!o"Drier()R
// : *base url*E used by selenium to resole relatie JI,s
$tring baseJrl ) *http?//www+google+com*R
// Create the $elenium implementation
$elenium selenium ) new TebDrierOac<ed$elenium(drierE baseJrl)R
// &er!orm actions with selenium
selenium+open(*http?//www+google+com*)R
selenium+type(*name)=*E *cheese*)R
selenium+clic<(*name)btnW*)R
// Wet the underlying TebDrier implementation bac<+ This will re!er to the
// same TebDrier instance as the *drier* ariable aboe+
TebDrier drierPnstance ) ((TebDrierOac<ed$elenium) selenium)+getTrappedDrier()R
//%inallyE close the browser+ Call stop on the TebDrierOac<ed$elenium instance
//instead o! calling drier+=uit()+ (therwiseE the YVN will continue running a!ter
//the browser has been closed+
selenium+stop()R
ros
Allo#s for the Web(ri.er and Selenium APIs to li.e side,by,side
Pro.ides a simple mechanism for a managed migration from the Selenium 2! API to Web(ri.ers
(oes not re0uire the standalone Selenium 2! ser.er to be run
Cons
(oes not implement e.ery method
*ore ad.anced Selenium usage ;using Dbro#serbotE or other built,in :a.aScript methods from Selenium !ore< may not #or'
Some methods may be slo#er due to underlying implementation differences
Bac%ing Web+ri'er 0ith Selenium
Web(ri.er doesnt support as many bro#sers as Selenium 2! does+ so in order to pro.ide that support #hile still using the Web(ri.er API+
you can ma'e use of the $eleneseCommand-"ecutor
Safari is supported in this #ay #ith the follo#ing code ;be sure to disable pop,up bloc'ing<1
DesiredCapabilities capabilities ) new DesiredCapabilities()R
capabilities+setOrowserQame(*sa!ari*)R
Command-"ecutor e"ecutor ) new $eleneseCommand-"ecutor(new JI,(*http?//localhost?/////*)E new
JI,(*http?//www+google+com/*)E capabilities)R
TebDrier drier ) new IemoteTebDrier(e"ecutorE capabilities)R
There are currently some major limitations #ith this approach+ notably that find&lements doesnt #or' as e%pected- Also+ because #ere
using Selenium !ore for the hea.y lifting of dri.ing the bro#ser+ you are limited by the :a.aScript sandbo%-
*unning Standalone Selenium Ser'er for use 0ith *emote+ri'ers
$rom Seleniums (o#nload page do#nload selenium,ser.er,standalone,U.ersionQ-jar and optionally I&(ri.erSer.er- If you plan to #or'
#ith !hrome+ do#nload it from >oogle !ode-
5npac' I&(ri.erSer.er andGor chromedri.er and put them in a directory #hich is on the _PATH G `PATH` , the Selenium Ser.er should
then be able to handle re0uests for I& G !hrome #ithout additional modifications-
Start the ser.er on the command line #ith
Kaa -Kar <pathSto>/selenium-serer-standalone-<ersion>+Kar
If you #ant to use nati.e e.ents functionality+ indicate this on the command line #ith the option
-Dwebdrier+enable+natie+eents)'
$or other command line options+ e%ecute
Kaa -Kar <pathSto>/selenium-serer-standalone-<ersion>+Kar -help
In order to function properly+ the follo#ing ports should be allo#ed incoming T!P connections1 9999+ I8L9,L ;or t#ice as many ports as the
number of concurrent instances you plan to run<- 5nder Windo#s+ you may need to unbloc' the applications as #ell-
Additional *esources
"ou can find further resources for Web(ri.er in Web(ri.ers #i'i
6f course+ dont hesitate to do an internet search on any Selenium topic+ including Selenium,Web(ri.ers dri.ers- There are 0uite a fe#
blogs on Selenium along #ith numerous posts on .arious user forums- Additionally the Selenium 5sers >roup is a great resource-
http1GGgroups-google-comGgroupGselenium,users
Ne3t Steps
This chapter has simply been a high le.el #al'through of Web(ri.er and some of its 'ey capabilities- 6nce getting familiar #ith the
Selenium,Web(ri.er API you #ill then #ant to learn ho# to build test suites for maintainability+ e%tensibility+ and reduced fragility #hen
features of the A5T fre0uently change- The approach most Selenium e%perts are no# recommending is to design your test code using the
Page 6bject (esign Pattern along #ith possibly a Page $actory- Selenium,Web(ri.er pro.ides support for this by supplying a Page$actory
class in :a.a and !H- This is presented+along #ith other ad.anced topics+ in the ne%t chapter- Also+ for high,le.el description of this
techni0ue+ you may #ant to loo' at the Test (esign !onsiderations chapter- Both of these chapters present techni0ues for #riting more
maintainable tests by ma'ing your test code more modular-
Table Of Contents
Web(ri.er1 Ad.anced 5sage
&%plicit and Implicit Waits
2emoteWeb(ri.er
Ad.anced5serInteractions
Bro#ser Startup *anipulation
HT*BL
Paralleli/ing "our Test 2uns
Web+ri'erK Ad'anced @sage
,3plicit and Implicit Waits
Waiting is ha.ing the automated tas' e%ecution elapse a certain amount of time before continuing #ith the ne%t step-
,3plicit Waits
An e%plicit #aits is code you define to #ait for a certain condition to occur before proceeding further in the code- The #orst case of this is
Thread-sleep;<+ #hich sets the condition to an e%act time period to #ait- There are some con.enience methods pro.ided that help you #rite
code that #ill #ait only as long as re0uired- Web(ri.erWait in combination #ith &%pected!ondition is one #ay this can be accomplished-
TebDrier drier ) new %ire!o"Drier()R
drier+get(*http?//somedomain/urlSthatSdelaysSloading*)R
Teb-lement myDynamic-lement ) (new TebDrierTait(drierE '5))
+until(-"pectedConditions+presence(!-lement,ocated(Oy+id(*myDynamic-lement*)))R
This #aits up to F8 seconds before thro#ing a Timeout&%ception or if it finds the element #ill return it in 8 , F8 seconds- Web(ri.erWait by
default calls the &%pected!ondition e.ery L88 milliseconds until it returns successfully- A successful return is for &%pected!ondition type is
Boolean return true or not null return .alue for all other &%pected!ondition types-
This e%ample is also functionally e0ui.alent to the first Implicit Waits e%ample-
,3pected Conditions
There are some common conditions that are fre0uently come across #hen automating #eb bro#sers- Bisted belo# are Implementations of
each- :a.a happens to ha.e con.ienence methods so you dont ha.e to code an &%pected!ondition class yourself or create your o#n utility
pac'age for them-
&lement is !lic'able , it is (isplayed and &nabled-
TebDrierTait wait ) new TebDrierTait(drierE '5)R
Teb-lement element ) wait+until(-"pectedConditions+elementToOeClic<able(Oy+id(*someid*)))R
The &%pected!onditions pac'age ;:a.a< ;Python< ;-N&T< contains a set of predefined conditions to use #ith Web(ri.erWait-
Implicit Waits
An implicit #ait is to tell Web(ri.er to poll the (6* for a certain amount of time #hen trying to find an element or elements if they are not
immediately a.ailable- The default setting is 8- 6nce set+ the implicit #ait is set for the life of the Web(ri.er object instance-
TebDrier drier ) new %ire!o"Drier()R
drier+manage()+timeouts()+implicitlyTait('5E TimeJnit+$-C(QD$)R
drier+get(*http?//somedomain/urlSthatSdelaysSloading*)R
Teb-lement myDynamic-lement ) drier+!ind-lement(Oy+id(*myDynamic-lement*))R
*emoteWeb+ri'er
Ta%ing a Screenshot
import Kaa+io+%ileR
import Kaa+net+JI,R
import org+open=a+selenium+(utputTypeR
import org+open=a+selenium+Ta<es$creenshotR
import org+open=a+selenium+TebDrierR
import org+open=a+selenium+remote+:ugmenterR
import org+open=a+selenium+remote+DesiredCapabilitiesR
import org+open=a+selenium+remote+IemoteTebDrierR
public class Testing D

public oid myTest() throws -"ception D
TebDrier drier ) new IemoteTebDrier(
new JI,(*http?//localhost?/////wd/hub*)E
DesiredCapabilities+!ire!o"())R

drier+get(*http?//www+google+com*)R

// IemoteTebDrier does not implement the Ta<es$creenshot class
// i! the drier does hae the Capabilities to ta<e a screenshot
// then :ugmenter will add the Ta<es$creenshot methods to the instance
TebDrier augmentedDrier ) new :ugmenter()+augment(drier)R
%ile screenshot ) ((Ta<es$creenshot)augmentedDrier)+
get$creenshot:s((utputType+%P,-)R
F
F
@sing a 2irefo3rofile
%ire!o"&ro!ile !p ) new %ire!o"&ro!ile()R
// set something on the pro!ile+++
DesiredCapabilities dc ) DesiredCapabilities+!ire!o"()R
dc+setCapability(%ire!o"Drier+&I(%P,-E !p)R
TebDrier drier ) new IemoteTebDrier(dc)R
@sing ChromeOptions
Chrome(ptions options ) new Chrome(ptions()R
// set some options
DesiredCapabilities dc ) DesiredCapabilities+chrome()R
dc+setCapability(Chrome(ptions+C:&:OP,PTME options)R
TebDrier drier ) new IemoteTebDrier(dc)R
Ad'anced@serInteractions
The Actions class;es< allo# you to build a !hain of Actions and perform them- There are too many possible combinations to count- Belo#
are a fe# of the common interactions that you may #ant to use- $or a full list of actions please refer to the API docs :a.a !H 2uby Python
The Ad.anced 5ser Interactions re0uire nati.e e.ents to be enabled- Heres a table of the current support *atri% for nati.e e.ents1
platform I,; I,: I,8 I,= 224&;
22)1
V
Chrome
stable
Chrome
beta
Chrome
de' Opera Android iOS
Windo#s
OP
" " " nGa " " " " " ? " RFS nGa
Windo#s
I
nGa nGa " " " " " " " ? " RFS nGa
Binu%
;5buntu<
nGa nGa nGa nGa " R7S " R7S " " " ? " RFS nGa
*ac 6SO nGa nGa nGa nGa N N " " " ? " RFS N
*obile
(e.ice
nGa nGa nGa nGa nGa ? nGa nGa nGa ? " N
RFS /F, 7, K, 90 5sing the emulator
R7S /F, 70 With e%plicitly enabling nati.e e.ents
Bro0ser Startup 7anipulation
Todo
Topics to be included1
restoring coo'ies
changing firefo% profile
running bro#sers #ith plugins
@sing a ro3y
Internet ,3plorer
The easiest and recommended #ay is to manually set the pro%y on the machine that #ill be running the test- If that is not possible or you
#ant your test to run #ith a different configuration or pro%y+ then you can use the follo#ing techni0ue that uses a !apababilities object- This
temporarily changes the systems pro%y settings and changes them bac' to the original state #hen done-
$tring &I(VM ) *localhost?3535*R
org+open=a+selenium+&ro"y pro"y ) new org+open=a+selenium+&ro"y()R
pro"y+setLttp&ro"y(&I(VM)
+set%tp&ro"y(&I(VM)
+set$sl&ro"y(&I(VM)R
DesiredCapabilities cap ) new DesiredCapabilities()R
cap+setCapability(CapabilityType+&I(VME pro"y)R
TebDrier drier ) new Pnternet-"plorerDrier(cap)R
Chrome
Is basically the same as internet e%plorer- It uses the same configuration on the machine as I& does ;on #indo#s<- 6n *ac it uses the System
Preference ,Q Net#or' settings- 6n Binu% it uses ;on 5buntu< System Q Preferences Q Net#or' Pro%y Preferences ;Alternati.ely in
DGetcGen.ironmentE set http\pro%y<- As of this #riting it is un'no#n ho# to set the pro%y programmatically-
2irefo3
$irefo% maintains its pro%y configuration in a profile- "ou can preset the pro%y in a profile and use that $irefo% Profile or you can set it on
profile that is created on the fly as is sho#n in the follo#ing e%ample-
$tring &I(VM ) *localhost?3535*R
org+open=a+selenium+&ro"y pro"y ) new org+open=a+selenium+&ro"y()R
pro"y+setLttp&ro"y(&I(VM)
+set%tp&ro"y(&I(VM)
+set$sl&ro"y(&I(VM)R
DesiredCapabilities cap ) new DesiredCapabilities()R
cap+setCapability(CapabilityType+&I(VME pro"y)R
TebDrier drier ) new %ire!o"Drier(cap)R
Opera
Todo
HT76T
Todo
aralleliLing /our Test *uns
Todo
Table Of Contents
Selenium F ;Selenium 2!<
Introduction
Ho# Selenium 2! Wor's
Installation
$rom Selenese to a Program
Programming "our Test
Bearning the API
2eporting 2esults
Adding Some Spice to "our Tests
Ser.er 6ptions
Specifying the Path to a Specific Bro#ser
Selenium 2! Architecture
Handling HTTPS and Security Popups
Supporting Additional Bro#sers and Bro#ser !onfigurations
Troubleshooting !ommon Problems
Selenium ) $Selenium *C(
Introduction
As you can read in Brief History of The Selenium Project+ Selenium 2! #as the main Selenium project for a long time+ before the
Web(ri.erGSelenium merge brought up Selenium 7+ the ne#est and more po#erful tool-
Selenium F is still acti.ely supported ;mostly in maintenance mode< and pro.ides some features that may not be a.ailable in Selenium 7 for
a #hile+ including support for se.eral languages ;:a.a+ :a.ascript+ 2uby+ PHP+ Python+ Perl and !H< and support for almost e.ery bro#ser out
there-
Ho0 Selenium *C Wor%s
$irst+ #e #ill describe ho# the components of Selenium 2! operate and the role each plays in running your test scripts-
*C Components
Selenium 2! components are1
The Selenium Ser.er #hich launches and 'ills bro#sers+ interprets and runs the Selenese commands passed from the test program+
and acts as an H& pro%y+ intercepting and .erifying HTTP messages passed bet#een the bro#ser and the A5T-
!lient libraries #hich pro.ide the interface bet#een each programming language and the Selenium 2! Ser.er-
Here is a simplified architecture diagram----

The diagram sho#s the client libraries communicate #ith the Ser.er passing each Selenium command for e%ecution- Then the ser.er passes
the Selenium command to the bro#ser using Selenium,!ore :a.aScript commands- The bro#ser+ using its :a.aScript interpreter+ e%ecutes
the Selenium command- This runs the Selenese action or .erification you specified in your test script-
Selenium Ser'er
Selenium Ser.er recei.es Selenium commands from your test program+ interprets them+ and reports bac' to your program the results of
running those tests-
The 2! ser.er bundles Selenium !ore and automatically injects it into the bro#ser- This occurs #hen your test program opens the bro#ser
;using a client library API function<- Selenium,!ore is a :a.aScript program+ actually a set of :a.aScript functions #hich interprets and
e%ecutes Selenese commands using the bro#sers built,in :a.aScript interpreter-
The Ser.er recei.es the Selenese commands from your test program using simple HTTP >&TGP6ST re0uests- This means you can use any
programming language that can send HTTP re0uests to automate Selenium tests on the bro#ser-
Client 6ibraries
The client libraries pro.ide the programming support that allo#s you to run Selenium commands from a program of your o#n design- There
is a different client library for each supported language- A Selenium client library pro.ides a programming interface ;API<+ i-e-+ a set of
functions+ #hich run Selenium commands from your o#n program- Within each interface+ there is a programming function that supports
each Selenese command-
The client library ta'es a Selenese command and passes it to the Selenium Ser.er for processing a specific action or test against the
application under test ;A5T<- The client library also recei.es the result of that command and passes it bac' to your program- "our program
can recei.e the result and store it into a program .ariable and report it as a success or failure+ or possibly ta'e correcti.e action if it #as an
une%pected error-
So to create a test program+ you simply #rite a program that runs a set of Selenium commands using a client library API- And+ optionally+ if
you already ha.e a Selenese test script created in the Selenium,I(&+ you can generate the "elenium *7 code- The Selenium,I(& can
translate ;using its &%port menu item< its Selenium commands into a client,dri.ers API function calls- See the Selenium,I(& chapter for
specifics on e%porting 2! code from Selenium,I(&-
Installation
Installation is rather a misnomer for Selenium- Selenium has set of libraries a.ailable in the programming language of your choice- "ou
could do#nload them from do#nloads page
6nce you.e chosen a language to #or' #ith+ you simply need to1
Install the Selenium 2! Ser.er-
Set up a programming project using a language specific client dri.er-
Installing Selenium Ser'er
The Selenium 2! ser.er is simply a :a.a Ear file ;selenium:server:standalone:Gversion:numberI.Ear<+ #hich doesnt re0uire any special
installation- :ust do#nloading the /ip file and e%tracting the ser.er in the desired directory is sufficient-
*unning Selenium Ser'er
Before starting any tests you must start the ser.er- >o to the directory #here Selenium 2!s ser.er is located and run the follo#ing from a
command,line console-
ja.a ,jar selenium,ser.er,standalone,U.ersion,numberQ-jar
This can be simplified by creating a batch or shell e%ecutable file ;-bat on Windo#s and -sh on Binu%< containing the command abo.e- Then
ma'e a shortcut to that e%ecutable on your des'top and simply double,clic' the icon to start the ser.er-
$or the ser.er to run youll need :a.a installed and the PATH en.ironment .ariable correctly configured to run it from the console- "ou can
chec' that you ha.e :a.a correctly installed by running the follo#ing on a console-
ja.a ,.ersion
If you get a .ersion number ;#hich needs to be F-L or later<+ youre ready to start using Selenium 2!-
@sing the Da'a Client +ri'er
(o#nload Selenium ja.a client dri.er /ip from the SeleniumH4 do#nloads page-
&%tract selenium,ja.a,U.ersion,numberQ-jar file
6pen your desired :a.a I(& ;&clipse+ NetBeans+ Intelli:+ Net#ea.er+ etc-<
!reate a ja.a project-
Add the selenium,ja.a,U.ersion,numberQ-jar files to your project as references-
Add to your project classpath the file selenium,ja.a,U.ersion,numberQ-jar-
$rom Selenium,I(&+ e%port a script to a :a.a file and include it in your :a.a project+ or #rite your Selenium test in :a.a using the
selenium,ja.a,client API- The API is presented later in this chapter- "ou can either use :5nit+ or TestNg to run your test+ or you can
#rite your o#n simple main;< program- These concepts are e%plained later in this section-
2un Selenium ser.er from the console-
&%ecute your test from the :a.a I(& or from the command,line-
$or details on :a.a test project configuration+ see the Appendi% sections !onfiguring Selenium 2! With &clipse and !onfiguring Selenium
2! With Intellij-
@sing the ython Client +ri'er
Install Selenium .ia PIP+ instructions lin'ed at SeleniumH4 do#nloads page
&ither #rite your Selenium test in Python or e%port a script from Selenium,I(& to a python file-
2un Selenium ser.er from the console
&%ecute your test from a console or your Python I(&
$or details on Python client dri.er configuration+ see the appendi% Python !lient (ri.er !onfiguration-
@sing the &N,T Client +ri'er
(o#nload Selenium 2! from the SeleniumH4 do#nloads page
&%tract the folder
(o#nload and install N5nit ; Note1 "ou can use N5nit as your test engine- If youre not familiar yet #ith N5nit+ you can also #rite a
simple main;< function to run your testsP ho#e.er N5nit is .ery useful as a test engine-<
6pen your desired -Net I(& ;3isual Studio+ Sharp(e.elop+ *ono(e.elop<
!reate a class library ;-dll<
Add references to the follo#ing (BBs1 nmoc'-dll+ nunit-core-dll+ nunit- frame#or'-dll+ ThoughtWor's-Selenium-!ore-dll+
ThoughtWor's-Selenium-IntegrationTests-dll and ThoughtWor's-Selenium-5nitTests-dll
Write your Selenium test in a -Net language ;!H+ 3B-Net<+ or e%port a script from Selenium,I(& to a !H file and copy this code into
the class file you just created-
Write your o#n simple main;< program or you can include N5nit in your project for running your test- These concepts are e%plained
later in this chapter-
2un Selenium ser.er from console
2un your test either from the I(&+ from the N5nit >5I or from the command line
$or specific details on -N&T client dri.er configuration #ith 3isual Studio+ see the appendi% -N&T client dri.er configuration-
@sing the *uby Client +ri'er
If you do not already ha.e 2uby>ems+ install it from 2uby$orge
2un gem install selenium-client
At the top of your test script+ add re=uire *selenium/client*
Write your test script using any 2uby test harness ;eg Test115nit+ *ini11Test or 2Spec<-
2un Selenium 2! ser.er from the console-
&%ecute your test in the same #ay you #ould run any other 2uby script-
$or details on 2uby client dri.er configuration+ see the Selenium,!lient documentation
2rom Selenese to a rogram
The primary tas' for using Selenium 2! is to con.ert your Selenese into a programming language- In this section+ #e pro.ide se.eral
different language,specific e%amples-
Sample Test Script
Bets start #ith an e%ample Selenese test script- Imagine recording the follo#ing test #ith Selenium,I(&-
open G
type 0 selenium
rc
clic'AndWait btn>
assertTe%tPresent 2esults N
for
selenium
rc

Note1 This e%ample #ould #or' #ith the >oogle search page http1GG###-google-com
Selenese as rogramming Code
Here is the test script e%ported ;.ia Selenium,I(&< to each of the supported programming languages- If you ha.e at least basic 'no#ledge of
an object, oriented programming language+ you #ill understand ho# Selenium runs Selenese commands by reading one of these e%amples-
To see an e%ample in a specific language+ select one of these buttons-
/@@ :dd YJnit !ramewor< to your classpath i! not already there
@ !or this e"ample to wor<
@/
pac<age com+e"ample+testsR
import com+thoughtwor<s+selenium+@R
import Kaa+util+rege"+&atternR
public class QewTest e"tends $eleneseTestCase D
public oid setJp() throws -"ception D
setJp(*http?//www+google+com/*E *@!ire!o"*)R
F
public oid testQew() throws -"ception D
selenium+open(*/*)R
selenium+type(*=*E *selenium rc*)R
selenium+clic<(*btnW*)R
selenium+wait%or&ageTo,oad(*.5555*)R
assertTrue(selenium+isTe"t&resent(*Iesults @ !or selenium rc*))R
F
F
In the ne%t section #ell e%plain ho# to build a test program using the generated code-
rogramming /our Test
No# #ell illustrate ho# to program your o#n tests using e%amples in each of the supported programming languages- There are essentially
t#o tas's1
>enerate your script into a programming language from Selenium,I(&+ optionally modifying the result-
Write a .ery simple main program that e%ecutes the generated code-
6ptionally+ you can adopt a test engine platform li'e :5nit or TestN> for :a.a+ or N5nit for -N&T if you are using one of those languages-
Here+ #e sho# language,specific e%amples- The language,specific APIs tend to differ from one to another+ so youll find a separate
e%planation for each-
:a.a
!H
Python
2uby
Perl+ PHP
Da'a
$or :a.a+ people use either :5nit or TestN> as the test engine- Some de.elopment en.ironments li'e &clipse ha.e direct support for these
.ia plug,ins- This ma'es it e.en easier- Teaching :5nit or TestN> is beyond the scope of this document ho#e.er materials may be found
online and there are publications a.ailable- If you are already a Dja.a,shopE chances are your de.elopers #ill already ha.e some e%perience
#ith one of these test frame#or's-
"ou #ill probably #ant to rename the test class from DNe#TestE to something of your o#n choosing- Also+ you #ill need to change the
bro#ser,open parameters in the statement1
selenium ) new De!ault$elenium(*localhost*E ////E *@iehta*E *http?//www+google+com/*)R
The Selenium,I(& generated code #ill loo' li'e this- This e%ample has comments added manually for additional clarity-
pac<age com+e"ample+testsR
// Te speci!y the pac<age o! our tests
import com+thoughtwor<s+selenium+@R
// This is the drier9s import+ Mou9ll use this !or instantiating a
// browser and ma<ing it do what you need+
import Kaa+util+rege"+&atternR
// $elenium-PD- add the &attern module because it9s sometimes used !or
// rege" alidations+ Mou can remoe the module i! it9s not used in your
// script+
public class QewTest e"tends $eleneseTestCase D
// Te create our $elenium test case
public oid setJp() throws -"ception D
setJp(*http?//www+google+com/*E *@!ire!o"*)R
// Te instantiate and start the browser
F
public oid testQew() throws -"ception D
selenium+open(*/*)R
selenium+type(*=*E *selenium rc*)R
selenium+clic<(*btnW*)R
selenium+wait%or&ageTo,oad(*.5555*)R
assertTrue(selenium+isTe"t&resent(*Iesults @ !or selenium rc*))R
// These are the real test steps
F
F
CU
The -N&T !lient (ri.er #or's #ith *icrosoft-N&T- It can be used #ith any -N&T testing frame#or' li'e N5nit or the 3isual Studio 788L
Team System-
Selenium,I(& assumes you #ill use N5nit as your testing frame#or'- "ou can see this in the generated code belo#- It includes the using
statement for N5nit along #ith corresponding N5nit attributes identifying the role for each member function of the test class-
"ou #ill probably ha.e to rename the test class from DNe#TestE to something of your o#n choosing- Also+ you #ill need to change the
bro#ser,open parameters in the statement1
selenium ) new De!ault$elenium(*localhost*E ////E *@iehta*E *http?//www+google+com/*)R
The generated code #ill loo' similar to this-
"ou can allo# N5nit to manage the e%ecution of your tests- 6r alternati.ely+ you can #rite a simple main;< program that instantiates the test
object and runs each of the three methods+ SetupTest;<+ TheNe#Test;<+ and Teardo#nTest;< in turn-
ython
Pyunit is the test frame#or' to use for Python- To learn Pyunit refer to its official documentation
Uhttp1GGdocs-python-orgGlibraryGunittest-htmlQ\-
The basic test structure is1
*uby
Selenium,I(& generates reasonable 2uby+ but re0uires the old Selenium gem- This is a problem because the official 2uby dri.er for
Selenium is the Selenium,!lient gem+ not the old Selenium gem- In fact+ the Selenium gem is no longer e.en under acti.e de.elopment-
Therefore+ it is ad.isable to update any 2uby scripts generated by the I(& as follo#s1
F- 6n line F+ change re=uire *selenium* to re=uire *selenium/client*
7- 6n line FF+ change $elenium??$eleniumDrier+new to $elenium??Client??Drier+new
"ou probably also #ant to change the class name to something more informati.e than D5ntitled+E and change the test methods name to
something other than Dtest\untitled-E
Here is a simple e%ample created by modifying the 2uby code generated by Selenium I(&+ as described abo.e-
erl5 H
The members of the documentation team ha.e not used Selenium 2! #ith Perl or PHP- If you are using Selenium 2! #ith either of these
t#o languages please contact the (ocumentation Team ;see the chapter on contributing<- We #ould lo.e to include some e%amples from you
and your e%periences+ to support Perl and PHP users-
6earning the AI
The Selenium 2! API uses naming con.entions that+ assuming you understand Selenese+ much of the interface #ill be self,e%planatory-
Here+ ho#e.er+ #e e%plain the most critical and possibly less ob.ious aspects-
Starting the Bro0ser
setJp(*http?//www+google+com/*E *@!ire!o"*)R
&ach of these e%amples opens the bro#ser and represents that bro#ser by assigning a Dbro#ser instanceE to a program .ariable- This
program .ariable is then used to call methods from the bro#ser- These methods e%ecute the Selenium commands+ i-e- li'e open or type or the
verify commands-
The parameters re0uired #hen creating the bro#ser instance are1
host
Specifies the IP address of the computer #here the ser.er is located- 5sually+ this is the same machine as #here the client is running+ so
in this case localhost is passed- In some clients this is an optional parameter-
port
Specifies the T!PGIP soc'et #here the ser.er is listening #aiting for the client to establish a connection- This also is optional in some
client dri.ers-
bro0ser
The bro#ser in #hich you #ant to run the tests- This is a re0uired parameter-
url
The base url of the application under test- This is re0uired by all the client libs and is integral information for starting up the bro#ser,
pro%y,A5T communication-
Note that some of the client libraries re0uire the bro#ser to be started e%plicitly by calling its start/0 method-
*unning Commands
6nce you ha.e the bro#ser initiali/ed and assigned to a .ariable ;generally named DseleniumE< you can ma'e it run Selenese commands by
calling the respecti.e methods from the bro#ser .ariable- $or e%ample+ to call the type method of the selenium object1
selenium-type;Dfield,idE+Estring to typeE<
In the bac'ground the bro#ser #ill actually perform a type operation+ essentially identical to a user typing input into the bro#ser+ by using
the locator and the string you specified during the method call-
*eporting *esults
Selenium 2! does not ha.e its o#n mechanism for reporting results- 2ather+ it allo#s you to build your reporting customi/ed to your needs
using features of your chosen programming language- Thats great+ but #hat if you simply #ant something 0uic' thats already done for
you? 6ften an e%isting library or test frame#or' can meet your needs faster than de.eloping your o#n test reporting code-
Test 2rame0or% *eporting Tools
Test frame#or's are a.ailable for many programming languages- These+ along #ith their primary function of pro.iding a fle%ible test engine
for e%ecuting your tests+ include library code for reporting results- $or e%ample+ :a.a has t#o commonly used test frame#or's+ :5nit and
TestN>- -N&T also has its o#n+ N5nit-
We #ont teach the frame#or's themsel.es hereP thats beyond the scope of this user guide- We #ill simply introduce the frame#or'
features that relate to Selenium along #ith some techni0ues you can apply- There are good boo's a.ailable on these test frame#or's
ho#e.er along #ith information on the internet-
Test *eport 6ibraries
Also a.ailable are third,party libraries specifically created for reporting test results in your chosen programming language- These often
support a .ariety of formats such as HT*B or P($-
What"s The Best Approach?
*ost people ne# to the testing frame#or's #ill begin #ith the frame#or's built,in reporting features- $rom there most #ill e%amine any
a.ailable libraries as thats less time consuming than de.eloping your o#n- As you begin to use Selenium no doubt you #ill start putting in
your o#n Dprint statementsE for reporting progress- That may gradually lead to you de.eloping your o#n reporting+ possibly in parallel to
using a library or test frame#or'- 2egardless+ after the initial+ but short+ learning cur.e you #ill naturally de.elop #hat #or's best for your
o#n situation-
Test *eporting ,3amples
To illustrate+ #ell direct you to some specific tools in some of the other languages supported by Selenium- The ones listed here are
commonly used and ha.e been used e%tensi.ely ;and therefore recommended< by the authors of this guide-
Test *eports in Da'a
If Selenium Test cases are de.eloped using :5nit then :5nit 2eport can be used to generate test reports- 2efer to :5nit 2eport for
specifics-
If Selenium Test cases are de.eloped using TestN> then no e%ternal tas' is re0uired to generate test reports- The TestN> frame#or'
generates an HT*B report #hich list details of tests- See TestN> 2eport for more-
2eportN> is a HT*B reporting plug,in for the TestN> frame#or'- It is intended as a replacement for the default TestN> HT*B
report- 2eportN> pro.ides a simple+ colour,coded .ie# of the test results- See 2eportN> for more-
Also+ for a .ery nice summary report try using TestN>,%slt- A TestN>,%slt 2eport loo's li'e this-

See TestN>,%slt for more-
6ogging the Selenese Commands
Bogging Selenium can be used to generate a report of all the Selenese commands in your test along #ith the success or failure of
each- Bogging Selenium e%tends the :a.a client dri.er to add this Selenese logging ability- Please refer to Bogging Selenium-
Test *eports for ython
When using Python !lient (ri.er then HT*BTest2unner can be used to generate a Test 2eport- See HT*BTest2unner-
Test *eports for *uby
If 2Spec frame#or' is used for #riting Selenium Test !ases in 2uby then its HT*B report can be used to generate a test report-
2efer to 2Spec 2eport for more-
Note
If you are interested in a language independent log of #hats going on+ ta'e a loo' at Selenium Ser.er Bogging
Adding Some Spice to /our Tests
No# #ell get to the #hole reason for using Selenium 2!+ adding programming logic to your tests- Its the same as for any program-
Program flo# is controlled using condition statements and iteration- In addition you can report progress information using IG6- In this section
#ell sho# some e%amples of ho# programming language constructs can be combined #ith Selenium to sol.e common testing problems-
"ou #ill find as you transition from the simple tests of the e%istence of page elements to tests of dynamic functionality in.ol.ing multiple
#eb,pages and .arying data that you #ill re0uire programming logic for .erifying e%pected results- Basically+ the Selenium,I(& does not
support iteration and standard condition statements- "ou can do some conditions by embedding ja.ascript in Selenese parameters+ ho#e.er
iteration is impossible+ and most conditions #ill be much easier in a programming language- In addition+ you may need e%ception handling
for error reco.ery- $or these reasons and others+ #e ha.e #ritten this section to illustrate the use of common programming techni0ues to gi.e
you greater ?.erification po#er in your automated testing-
The e%amples in this section are #ritten in !H and :a.a+ although the code is simple and can be easily adapted to the other supported
languages- If you ha.e some basic 'no#ledge of an object,oriented programming language you shouldnt ha.e difficulty understanding this
section-
Iteration
Iteration is one of the most common things people need to do in their tests- $or e%ample+ you may #ant to to e%ecute a search multiple times-
6r+ perhaps for .erifying your test results you need to process a Dresult setE returned from a database-
5sing the same >oogle search e%ample #e used earlier+ lets chec' the Selenium search results- This test could use the Selenese1
open G
type 0 selenium
rc
clic'AndWait btn>
assertTe%tPresent 2esults N
for
selenium
rc
type 0 selenium
ide
clic'AndWait btn>
assertTe%tPresent 2esults N
for
selenium
ide

type 0 selenium
grid
clic'AndWait btn>
assertTe%tPresent 2esults N
for
selenium
grid

The code has been repeated to run the same steps K times- But multiple copies of the same code is not good program practice because its
more #or' to maintain- By using a programming language+ #e can iterate o.er the search results for a more fle%ible and maintainable
solution-
In CUK
// Collection o! $tring alues+
$tring67 arr ) D*ide*E *rc*E *grid*FR
// -"ecute loop !or each $tring in array 9arr9+
!oreach ($tring s in arr) D
sel+open(*/*)R
sel+type(*=*E *selenium * Cs)R
sel+clic<(*btnW*)R
sel+wait%or&ageTo,oad(*.5555*)R
assertTrue(*-"pected te"t? * CsC * is missing on page+*
E sel+isTe"t&resent(*Iesults @ !or selenium * C s))R
F
Condition Statements
To illustrate using conditions in tests #ell start #ith an e%ample- A common problem encountered #hile running Selenium tests occurs
#hen an e%pected element is not a.ailable on page- $or e%ample+ #hen running the follo#ing line1
selenium+type(*=*E *selenium * Cs)R
If element ?0 is not on the page then an e%ception is thro#n1
com+thoughtwor<s+selenium+$elenium-"ception? -II(I? -lement = not !ound
This can cause your test to abort- $or some tests thats #hat you #ant- But often that is not desirable as your test script has many other
subse0uent tests to perform-
A better approach is to first .alidate #hether the element is really present and then ta'e alternati.es #hen it it is not- Bets loo' at this using
:a.a-
// P! element is aailable on page then per!orm type operation+
i!(selenium+is-lement&resent(*=*)) D
selenium+type(*=*E *$elenium rc*)R
F else D
$ystem+out+print!(*-lement? * C=C * is not aailable on page+*)
F
The ad.antage of this approach is to continue #ith test e%ecution e.en if some 5I elements are not a.ailable on page-
,3ecuting Da'aScript from /our Test
:a.aScript comes .ery handy in e%ercising an application #hich is not directly supported by selenium- The get,'al method of selenium API
can be used to e%ecute :a.aScript from selenium 2!-
!onsider an application ha.ing chec' bo%es #ith no static identifiers- In this case one could e.aluate :a.aScript from selenium 2! to get ids
of all chec' bo%es and then e%ercise them-
public static $tring67 get:llChec<bo"Pds () D
$tring script ) *ar inputPd ) new :rray()R*R// Create array in Kaa script+
script C) *ar cnt ) 5R*R // Counter !or chec< bo" ids+
script C) *ar input%ields ) new :rray()R*R // Create array in Kaa script+
script C) *input%ields ) window+document+get-lementsOyTagQame(9input9)R*R // Collect input
elements+
script C) *!or(ar i)5R i<input%ields+lengthR iCC) D*R // ,oop through the collected elements+
script C) *i!(input%ields6i7+id !)null * C
*\\ input%ields6i7+id !)9unde!ined9 * C
*\\ input%ields6i7+get:ttribute(9type9) )) 9chec<bo"9) D*R // P! input !ield is o! type chec< bo"
and input id is not null+
script C) *inputPd6cnt7)input%ields6i7+id R* C // $ae chec< bo" id to inputPd array+
*cntCCR* C // increment the counter+
*F* C // end o! i!+
*F*R // end o! !or+
script C) *inputPd+to$tring()R* R// Conert array in to string+
$tring67 chec<bo"Pds ) selenium+get-al(script)+split(*E*)R // $plit the string+
return chec<bo"PdsR
F
To count number of images on a page1
selenium+get-al(*window+document+images+lengthR*)R
2emember to use #indo# object in case of (6* e%pressions as by default selenium #indo# is referred to+ not the test #indo#-
Ser'er Options
When the ser.er is launched+ command line options can be used to change the default ser.er beha.iour-
2ecall+ the ser.er is started by running the follo#ing-
Z Kaa -Kar selenium-serer-standalone-<ersion-number>+Kar
To see the list of options+ run the ser.er #ith the -h option-
Z Kaa -Kar selenium-serer-standalone-<ersion-number>+Kar -h
"oull see a list of all the options you can use #ith the ser.er and a brief description of each- The pro.ided descriptions #ill not al#ays be
enough+ so #e.e pro.ided e%planations for some of the more important options-
ro3y Configuration
If your A5T is behind an HTTP pro%y #hich re0uires authentication then you should configure http-pro%yHost+ http-pro%yPort+
http-pro%y5ser and http-pro%yPass#ord using the follo#ing command-
Z Kaa -Kar selenium-serer-standalone-<ersion-number>+Kar -Dhttp+pro"yLost)pro"y+com -Dhttp+pro"y&ort)3535
-Dhttp+pro"yJser)username -Dhttp+pro"y&assword)password
7ulti-Windo0 7ode
If you are using Selenium F-8 you can probably s'ip this section+ since multi#indo# mode is the default beha.ior- Ho#e.er+ prior to .ersion
F-8+ Selenium by default ran the application under test in a sub frame as sho#n here-

Some applications didnt run correctly in a sub frame+ and needed to be loaded into the top frame of the #indo#- The multi,#indo# mode
option allo#ed the A5T to run in a separate #indo# rather than in the default frame #here it could then ha.e the top frame it re0uired-

$or older .ersions of Selenium you must specify multi#indo# mode e%plicitly #ith the follo#ing option1
-multiwindow
As of Selenium 2! F-8+ if you #ant to run your test #ithin a single frame ;i-e- using the standard for earlier Selenium .ersions< you can state
this to the Selenium Ser.er using the option
-singlewindow
Specifying the 2irefo3 rofile
$irefo% #ill not run t#o instances simultaneously unless you specify a separate profile for each instance- Selenium 2! F-8 and later runs in a
separate profile automatically+ so if you are using Selenium F-8+ you can probably s'ip this section- Ho#e.er+ if youre using an older
.ersion of Selenium or if you need to use a specific profile for your tests ;such as adding an https certificate or ha.ing some addons
installed<+ you #ill need to e%plicitly specify the profile-
$irst+ to create a separate $irefo% profile+ follo# this procedure- 6pen the Windo#s Start menu+ select D2unE+ then type and enter one of the
follo#ing1
!ire!o"+e"e -pro!ilemanager
!ire!o"+e"e -&
!reate the ne# profile using the dialog- Then #hen you run Selenium Ser.er+ tell it to use this ne# $irefo% profile #ith the ser.er command,
line option :firefo%&rofileemplate and specify the path to the profile using its filename and directory path-
-!ire!o"&ro!ileTemplate *path to the pro!ile*
Warning
Be sure to put your profile in a ne# folder separate from the defaultZZZ The $irefo% profile manager tool #ill delete all files in a folder if you
delete a profile+ regardless of #hether they are profile files or not-
*ore information about $irefo% profiles can be found in *o/illas Ano#ledge Base
*un Selenese +irectly Within the Ser'er @sing -htmlSuite
"ou can run Selenese html files directly #ithin the Selenium Ser.er by passing the html file to the ser.ers command line- $or instance1
Kaa -Kar selenium-serer-standalone-<ersion-number>+Kar -html$uite *@!ire!o"*
*http?//www+google+com* *c?]absolute]path]to]my]LTN,$uite+html*
*c?]absolute]path]to]my]results+html*
This #ill automatically launch your HT*B suite+ run all the tests and sa.e a nice HT*B report #ith the results-
Note
When using this option+ the ser.er #ill start the tests and #ait for a specified number of seconds for the test to completeP if the test doesnt
complete #ithin that amount of time+ the command #ill e%it #ith a non,/ero e%it code and no results file #ill be generated-
This command line is .ery long so be careful #hen you type it- Note this re0uires you to pass in an HT*B Selenese suite+ not a single test-
Also be a#are the ,htmlSuite option is incompatible #ith -interactie "ou cannot run both at the same time-
Selenium Ser'er 6ogging
Ser'er-Side 6ogs
When launching selenium ser.er the -log option can be used to record .aluable debugging information reported by the Selenium Ser.er to a
te%t file-
Kaa -Kar selenium-serer-standalone-<ersion-number>+Kar -log selenium+log
This log file is more .erbose than the standard console logs ;it includes (&B5> le.el logging messages<- The log file also includes the
logger name+ and the I( number of the thread that logged the message- $or e%ample1
#5?//?#0 D-OJW 6'#7 org+open=a+selenium+serer+$eleniumDrierIesourceLandler -
Orowser /103#3/?top !rame' posted $T:IT Q-T
The message format is
TPN-$T:N&(LL?mm?ss) ,-V-, 6TLI-:D7 ,(WW-I - N-$$:W-
This message may be multiline-
Bro0ser-Side 6ogs
:a.aScript on the bro#ser side ;Selenium !ore< also logs important messagesP in many cases+ these can be more useful to the end,user than
the regular Selenium Ser.er logs- To access bro#ser,side logs+ pass the -bro0serSide6og argument to the Selenium Ser.er-
Kaa -Kar selenium-serer-standalone-<ersion-number>+Kar -browser$ide,og
-bro0serSide6og must be combined #ith the -log argument+ to log bro#serSideBogs ;as #ell as all other (&B5> le.el logging messages<
to a file-
Specifying the ath to a Specific Bro0ser
"ou can specify to Selenium 2! a path to a specific bro#ser- This is useful if you ha.e different .ersions of the same bro#ser and you #ish
to use a specific one- Also+ this is used to allo# your tests to run against a bro#ser not directly supported by Selenium 2!- When specifying
the run mode+ use the Ncustom specifier follo#ed by the full path to the bro#sers e%ecutable1
@custom <path to browser>
Selenium *C Architecture
Note
This topic tries to e%plain the technical implementation behind Selenium 2!- Its not fundamental for a Selenium user to 'no# this+ but
could be useful for understanding some of the problems you might find in the future-
To understand in detail ho# Selenium 2! Ser.er #or's and #hy it uses pro%y injection and heightened pri.ilege modes you must first
understand the same origin policy-
The Same Origin olicy
The main restriction that Selenium faces is the Same 6rigin Policy- This security restriction is applied by e.ery bro#ser in the mar'et and its
objecti.e is to ensure that a sites content #ill ne.er be accessible by a script from another site- The Same 6rigin Policy dictates that any
code loaded #ithin the bro#ser can only operate #ithin that #ebsites domain- It cannot perform functions on another #ebsite- So for
e%ample+ if the bro#ser loads :a.aScript code #hen it loads ###-mysite-com+ it cannot run that loaded code against ###-mysite7-com)
e.en if thats another of your sites- If this #ere possible+ a script placed on any #ebsite you open #ould be able to read information on your
ban' account if you had the account page opened on other tab- This is called OSS ;!ross,site Scripting<-
To #or' #ithin this policy+ Selenium,!ore ;and its :a.aScript commands that ma'e all the magic happen< must be placed in the same origin
as the Application 5nder Test ;same 52B<-
Historically+ Selenium,!ore #as limited by this problem since it #as implemented in :a.aScript- Selenium 2! is not+ ho#e.er+ restricted by
the Same 6rigin Policy- Its use of the Selenium Ser.er as a pro%y a.oids this problem- It+ essentially+ tells the bro#ser that the bro#ser is
#or'ing on a single DspoofedE #ebsite that the Ser.er pro.ides-
Note
"ou can find additional information about this topic on Wi'ipedia pages about Same 6rigin Policy and OSS-
ro3y In!ection
The first method Selenium used to a.oid the The Same 6rigin Policy #as Pro%y Injection- In Pro%y Injection *ode+ the Selenium Ser.er
acts as a client,configured RFS HTT pro3y R7S+ that sits bet#een the bro#ser and the Application 5nder Test- It then mas's the A5T under a
fictional 52B ;embedding Selenium,!ore and the set of tests and deli.ering them as if they #ere coming from the same origin<-
RFS The pro%y is a third person in the middle that passes the ball bet#een the t#o parts- It acts as a D#eb ser.erE that deli.ers the A5T to the
bro#ser- Being a pro%y gi.es Selenium Ser.er the capability of DlyingE about the A5Ts real 52B-
R7S The bro#ser is launched #ith a configuration profile that has set localhost19999 as the HTTP pro%y+ this is #hy any HTTP re0uest that
the bro#ser does #ill pass through Selenium ser.er and the response #ill pass through it and not from the real ser.er-
Here is an architectural diagram-

As a test suite starts in your fa.orite language+ the follo#ing happens1
F- The clientGdri.er establishes a connection #ith the selenium,2! ser.er-
7- Selenium 2! ser.er launches a bro#ser ;or reuses an old one< #ith a 52B that injects Selenium,!ores :a.aScript into the bro#ser,
loaded #eb page-
K- The client,dri.er passes a Selenese command to the ser.er-
9- The Ser.er interprets the command and then triggers the corresponding :a.aScript e%ecution to e%ecute that command #ithin the
bro#ser- Selenium,!ore instructs the bro#ser to act on that first instruction+ typically opening a page of the A5T-
L- The bro#ser recei.es the open re0uest and as's for the #ebsites content from the Selenium 2! ser.er ;set as the HTTP pro%y for the
bro#ser to use<-
=- Selenium 2! ser.er communicates #ith the Web ser.er as'ing for the page and once it recei.es it+ it sends the page to the bro#ser
mas'ing the origin to loo' li'e the page comes from the same ser.er as Selenium,!ore ;this allo#s Selenium,!ore to comply #ith
the Same 6rigin Policy<-
I- The bro#ser recei.es the #eb page and renders it in the frameG#indo# reser.ed for it-
Heightened ri'ileges Bro0sers
This #or'flo# in this method is .ery similar to Pro%y Injection but the main difference is that the bro#sers are launched in a special mode
called Heightened &rivileges+ #hich allo#s #ebsites to do things that are not commonly permitted ;as doing OSS+ or filling file upload
inputs and pretty useful stuff for Selenium<- By using these bro#ser modes+ Selenium !ore is able to directly open the A5T and readGinteract
#ith its content #ithout ha.ing to pass the #hole A5T through the Selenium 2! ser.er-
Here is the architectural diagram-

As a test suite starts in your fa.orite language+ the follo#ing happens1
F- The clientGdri.er establishes a connection #ith the selenium,2! ser.er-
7- Selenium 2! ser.er launches a bro#ser ;or reuses an old one< #ith a 52B that #ill load Selenium,!ore in the #eb page-
K- Selenium,!ore gets the first instruction from the clientGdri.er ;.ia another HTTP re0uest made to the Selenium 2! Ser.er<-
9- Selenium,!ore acts on that first instruction+ typically opening a page of the A5T-
L- The bro#ser recei.es the open re0uest and as's the Web Ser.er for the page- 6nce the bro#ser recei.es the #eb page+ renders it in
the frameG#indo# reser.ed for it-
Handling HTTS and Security opups
*any applications s#itch from using HTTP to HTTPS #hen they need to send encrypted information such as pass#ords or credit card
information- This is common #ith many of todays #eb applications- Selenium 2! supports this-
To ensure the HTTPS site is genuine+ the bro#ser #ill need a security certificate- 6ther#ise+ #hen the bro#ser accesses the A5T using
HTTPS+ it #ill assume that application is not ?trusted- When this occurs the bro#ser displays security popups+ and these popups cannot be
closed using Selenium 2!-
When dealing #ith HTTPS in a Selenium 2! test+ you must use a run mode that supports this and handles the security certificate for you-
"ou specify the run mode #hen your test program initiali/es Selenium-
In Selenium 2! F-8 beta 7 and later use Nfirefo% or Nie%plore for the run mode- In earlier .ersions+ including Selenium 2! F-8 beta F+ use
Nchrome or Niehta+ for the run mode- 5sing these run modes+ you #ill not need to install any special security certificatesP Selenium 2! #ill
handle it for you-
In .ersion F-8 the run modes Nfirefo% or Nie%plore are recommended- Ho#e.er+ there are additional run modes of Nie%plorepro%y and
Nfirefo%pro%y- These are pro.ided for bac'#ards compatibility only+ and should not be used unless re0uired by legacy test programs- Their
use #ill present limitations #ith security certificate handling and #ith the running of multiple #indo#s if your application opens additional
bro#ser #indo#s-
In earlier .ersions of Selenium 2!+ Nchrome or Niehta #ere the run modes that supported HTTPS and the handling of security popups- These
#ere considered abce%perimental modes although they became 0uite stable and many people used them- If you are using Selenium F-8 you
do not need+ and should not use+ these older run modes-
Security Certificates ,3plained
Normally+ your bro#ser #ill trust the application you are testing by installing a security certificate #hich you already o#n- "ou can chec'
this in your bro#sers options or Internet properties ;if you dont 'no# your A5Ts security certificate as' your system administrator<- When
Selenium loads your bro#ser it injects code to intercept messages bet#een the bro#ser and the ser.er- The bro#ser no# thin's untrusted
soft#are is trying to loo' li'e your application- It responds by alerting you #ith popup messages-
To get around this+ Selenium 2!+ ;again #hen using a run mode that support this< #ill install its o#n security certificate+ temporarily+ to your
client machine in a place #here the bro#ser can access it- This tric's the bro#ser into thin'ing its accessing a site different from your A5T
and effecti.ely suppresses the popups-
Another method used #ith earlier .ersions of Selenium #as to install the !yber.illians security certificate pro.ided #ith your Selenium
installation- *ost users should no longer need to do this ho#e.erP if you are running Selenium 2! in pro%y injection mode+ you may need to
e%plicitly install this security certificate-
Supporting Additional Bro0sers and Bro0ser Configurations
The Selenium API supports running against multiple bro#sers in addition to Internet &%plorer and *o/illa $irefo%- See the SeleniumH4-org
#ebsite for supported bro#sers- In addition+ #hen a bro#ser is not directly supported+ you may still run your Selenium tests against a
bro#ser of your choosing by using the DNcustomE run,mode ;i-e- in place of Nfirefo% or Nie%plore< #hen your test application starts the
bro#ser- With this+ you pass in the path to the bro#sers e%ecutable #ithin the API call- This can also be done from the Ser.er in interacti.e
mode-
cmd)getQewOrowser$ession\')@custom c?]&rogram %iles]NoAilla %ire!o"]NyOrowser+e"e\#)http?//www+google+com
*unning Tests 0ith +ifferent Bro0ser Configurations
Normally Selenium 2! automatically configures the bro#ser+ but if you launch the bro#ser using the DNcustomE run mode+ you can force
Selenium 2! to launch the bro#ser as,is+ #ithout using an automatic configuration-
$or e%ample+ you can launch $irefo% #ith a custom configuration li'e this1
cmd)getQewOrowser$ession\')@custom c?]&rogram %iles]NoAilla %ire!o"]!ire!o"+e"e\#)http?//www+google+com
Note that #hen launching the bro#ser this #ay+ you must manually configure the bro#ser to use the Selenium Ser.er as a pro%y- Normally
this just means opening your bro#ser preferences and specifying Dlocalhost19999E as an HTTP pro%y+ but instructions for this can differ
radically from bro#ser to bro#ser- !onsult your bro#sers documentation for details-
Be a#are that *o/illa bro#sers can .ary in ho# they start and stop- 6ne may need to set the *6d\N6\2&*6T& en.ironment .ariable to
ma'e *o/illa bro#sers beha.e a little more predictably- 5ni% users should a.oid launching the bro#ser using a shell scriptP its generally
better to use the binary e%ecutable ;e-g- firefo%,bin< directly-
Troubleshooting Common roblems
When getting started #ith Selenium 2! theres a fe# potential problems that are commonly encountered- We present them along #ith their
solutions here-
@nable to Connect to Ser'er
When your test program cannot connect to the Selenium Ser.er+ Selenium thro#s an e%ception in your test program- It should display this
message or a similar one1
*Jnable to connect to remote serer (Pnner -"ception Nessage?
Qo connection could be made because the target machine actiely
re!used it )*
(using +Q-T and V& $erice &ac< #)
If you see a message li'e this+ be sure you started the Selenium Ser.er- If so+ then there is a problem #ith the connecti.ity bet#een the
Selenium !lient Bibrary and the Selenium Ser.er-
When starting #ith Selenium 2!+ most people begin by running thier test program ;#ith a Selenium !lient Bibrary< and the Selenium Ser.er
on the same machine- To do this use DlocalhostE as your connection parameter- We recommend beginning this #ay since it reduces the
influence of potential net#or'ing problems #hich youre getting started- Assuming your operating system has typical net#or'ing and
T!PGIP settings you should ha.e little difficulty- In truth+ many people choose to run the tests this #ay-
If+ ho#e.er+ you do #ant to run Selenium Ser.er on a remote machine+ the connecti.ity should be fine assuming you ha.e .alid T!PGIP
connecti.ity bet#een the t#o machines-
If you ha.e difficulty connecting+ you can use common net#or'ing tools li'e ping+ telnet+ ifconfig/)ni%06ipconfig ;Windo#s<+ etc to ensure
you ha.e a .alid net#or' connection- If unfamilar #ith these+ your system administrator can assist you-
@nable to 6oad the Bro0ser
6'+ not a friendly error message+ sorry+ but if the Selenium Ser.er cannot load the bro#ser you #ill li'ley see this error-
(055) Pnternal $erer -rror
This could be caused by
$irefo% ;prior to Selenium F-8< cannot start because the bro#ser is already open and you did not specify a separate profile- See the
section on $irefo% profiles under Ser.er 6ptions-
The run mode youre using doesnt match any bro#ser on your machine- !hec' the parameters you passed to Selenium #hen you
program opens the bro#ser-
"ou specified the path to the bro#ser e%plicitly ;using DNcustomE)see abo.e< but the path is incorrect- !hec' to be sure the path is
correct- Also chec' the user group to be sure there are no 'no#n issues #ith your bro#ser and the DNcustomE parameters-
Selenium Cannot 2ind the A@T
If your test program starts the bro#ser successfully+ but the bro#ser doesnt display the #ebsite youre testing+ the most li'ely cause is your
test program is not using the correct 52B-
This can easily happen- When you use Selenium,I(& to e%port your script+ it inserts a dummy 52B- "ou must manually change the 52B to
the correct one for your application to be tested-
2irefo3 *efused Shutdo0n While reparing a rofile
This most often occurs #hen your run your Selenium 2! test program against $irefo%+ but you already ha.e a $irefo% bro#ser session
running and+ you didnt specify a separate profile #hen you started the Selenium Ser.er- The error from the test program loo's li'e this1
-rror? Kaa+lang+Iuntime-"ception? %ire!o" re!used shutdown while
preparing a pro!ile
Heres the complete error message from the ser.er1
'1?#5?5.+4'4 PQ%( - &reparing %ire!o" pro!ile+++
'1?#5?#2+3## T:IQ - W-T /selenium-serer/drier/;cmd)getQewOrowser$ession\')@!ir
e!o"\#)http[.a[#![#!sage-webapp'+=a+idc+com LTT&/'+'
Kaa+lang+Iuntime-"ception? %ire!o" re!used shutdown while preparing a pro!ile
at org+open=a+selenium+serer+browserlaunchers+%ire!o"Custom&ro!ile,aunc
her+wait%or%ull&ro!ileToOeCreated(%ire!o"Custom&ro!ile,auncher+Kaa?#22)
+++
Caused by? org+open=a+selenium+serer+browserlaunchers+%ire!o"Custom&ro!ile,aunc
herZ%ile,oc<Iemained-"ception? ,oc< !ile still present! C?]D(CJN-^']Ksec],(C:,$
^']Temp]custom&ro!ileDir#5.'.3]parent+loc<
To resol.e this+ see the section on Specifying a Separate $irefo% Profile
Aersioning roblems
*a'e sure your .ersion of Selenium supports the .ersion of your bro#ser- $or e%ample+ Selenium 2! 8-C7 does not support $irefo% K- At
times you may be luc'y ;I #as<- But dont forget to chec' #hich bro#ser .ersions are supported by the .ersion of Selenium you are using-
When in doubt+ use the latest release .ersion of Selenium #ith the most #idely used .ersion of your bro#ser-
,rror messageK B$@nsupported ma!or&minor 'ersion <=&1(C 0hile starting ser'er
This error says youre not using a correct .ersion of :a.a- The Selenium Ser.er re0uires :a.a F-L or higher-
To chec' double,chec' your ja.a .ersion+ run this from the command line-
Kaa -ersion
"ou should see a message sho#ing the :a.a .ersion-
Kaa ersion *'+0+5S52*
Yaa(TN) # Iuntime -nironmentE $tandard -dition (build '+0+5S52-b5.)
Yaa Lot$pot(TN) Client VN (build '+0+5S52-b5.E mi"ed mode)
If you see a lo#er .ersion number+ you may need to update the :2&+ or you may simply need to add it to your PATH en.ironment .ariable-
<1< error 0hen running the getNe0Bro0serSession command
If youre getting a 989 error #hile attempting to open a page on Dhttp1GG###-google-comGselenium,ser.erGE+ then it must be because the
Selenium Ser.er #as not correctly configured as a pro%y- The Dselenium,ser.erE directory doesnt e%ist on google-comP it only appears to
e%ist #hen the pro%y is properly configured- Pro%y !onfiguration highly depends on ho# the bro#ser is launched #ith Nfirefo%+ Nie%plore+
Nopera+ or Ncustom-
Nie%plore1 If the bro#ser is launched using Nie%plore+ you could be ha.ing a problem #ith Internet &%plorers
pro%y settings- Selenium Ser.er attempts To configure the global pro%y settings in the Internet 6ptions
!ontrol Panel- "ou must ma'e sure that those are correctly configured #hen Selenium Ser.er launches the
bro#ser- Try loo'ing at your Internet 6ptions control panel- !lic' on the D!onnectionsE tab and clic' on
DBAN SettingsE-
If you need to use a pro%y to access the application you #ant to test+ youll need to start Selenium
Ser.er #ith D,(http-pro%yHostEP see the Pro%y !onfiguration for more details-
"ou may also try configuring your pro%y manually and then launching the bro#ser #ith Ncustom+ or
#ith Niehta bro#ser launcher-
Ncustom1 When using Ncustom you must configure the pro%y correctly;manually<+
other#ise youll get a 989 error- (ouble,chec' that you.e configured your pro%y settings correctly- To chec'
#hether you.e configured the pro%y correctly is to attempt to intentionally configure the bro#ser incorrectly- Try
configuring the bro#ser to use the #rong pro%y ser.er hostname+ or the #rong port- If you had successfully
configured the bro#sers pro%y settings incorrectly+ then the bro#ser #ill be unable to connect to the Internet+
#hich is one #ay to ma'e sure that one is adjusting the rele.ant settings-
$or other bro#sers ;Nfirefo%+ Nopera< #e automatically hard,code the pro%y for you+ and so ther are no 'no#n issues #ith
this functionality- If youre encountering 989 errors and ha.e follo#ed this user guide carefully post your results to user
group for some help from the user community-
ermission +enied ,rror
The most common reason for this error is that your session is attempting to .iolate the same,origin policy by crossing domain boundaries
;e-g-+ accesses a page from http1GGdomainF and then accesses a page from http1GGdomain7< or s#itching protocols ;mo.ing from
http1GGdomainO to https1GGdomainO<-
This error can also occur #hen :a.aScript attempts to find 5I objects #hich are not yet a.ailable ;before the page has completely loaded<+ or
are no longer a.ailable ;after the page has started to be unloaded<- This is most typically encountered #ith A:AO pages #hich are #or'ing
#ith sections of a page or subframes that load andGor reload independently of the larger page-
This error can be intermittent- 6ften it is impossible to reproduce the problem #ith a debugger because the trouble stems from race
conditions #hich are not reproducible #hen the debuggers o.erhead is added to the system- Permission issues are co.ered in some detail in
the tutorial- 2ead the section about the The Same 6rigin Policy+ Pro%y Injection carefully-
Handling Bro0ser opup Windo0s
There are se.eral 'inds of DPopupsE that you can get during a Selenium test- "ou may not be able to close these popups by running selenium
commands if they are initiated by the bro#ser and not your A5T- "ou may need to 'no# ho# to manage these- &ach type of popup needs to
be addressed differently-
HTTP basic authentication dialogs1 These dialogs prompt for a usernameGpass#ord to login to the site- To login to a site
that re0uires HTTP basic authentication+ use a username and pass#ord in the 52B+ as described in 2$! FIK@+ li'e this1
open;Dhttp1GGmyusername1myuserpass#ord]mye%ample-comGblahGblahGblahE<-
SSB certificate #arnings1 Selenium 2! automatically attempts to spoof SSB certificates #hen it is enabled as a pro%yP see
more on this in the section on HTTPS- If your bro#ser is configured correctly+ you should ne.er see SSB certificate
#arnings+ but you may need to configure your bro#ser to trust our dangerous D!yber3illainsE SSB certificate authority-
Again+ refer to the HTTPS section for ho# to do this-
modal :a.aScript alertGconfirmationGprompt dialogs1 Selenium tries to conceal those dialogs from you ;by replacing
#indo#-alert+ #indo#-confirm and #indo#-prompt< so they #ont stop the e%ecution of your page- If youre seeing an
alert pop,up+ its probably because it fired during the page load process+ #hich is usually too early for us to protect the
page- Selenese contains commands for asserting or .erifying alert and confirmation popups- See the sections on these
topics in !hapter 9-
On 6inu35 0hy isn"t my 2irefo3 bro0ser session closing?
6n 5ni%GBinu% you must in.o'e Dfirefo%,binE directly+ so ma'e sure that e%ecutable is on the path- If e%ecuting $irefo% through a shell
script+ #hen it comes time to 'ill the bro#ser Selenium 2! #ill 'ill the shell script+ lea.ing the bro#ser running- "ou can specify the path to
firefo%,bin directly+ li'e this-
cmd)getQewOrowser$ession\')@!ire!o" /usr/local/!ire!o"/!ire!o"-bin\#)http?//www+google+com
2irefo3 9chrome doesn"t 0or% 0ith custom profile
!hec' $irefo% profile folder ,Q prefs-js ,Q user\pref;Dbro#ser-startup-pageE+ 8<P !omment this line li'e this1
DGGuser\pref;Dbro#ser-startup-pageE+ 8<PE and try again-
Is it o% to load a custom pop-up as the parent page is loading $i&e&5 before the parent page"s !a'ascript
0indo0&onload$( function runs(?
No- Selenium relies on interceptors to determine #indo# names as they are being loaded- These interceptors #or' best in catching ne#
#indo#s if the #indo#s are loaded A$T&2 the onload;< function- Selenium may not recogni/e #indo#s loaded before the onload function-
roblems With Aerify Commands
If you e%port your tests from Selenium,I(&+ you may find yourself getting empty .erify strings from your tests ;depending on the
programming language used<-
Note: his section is not yet developed.
Safari and 7ultiWindo0 7ode
Note: his section is not yet developed.
2irefo3 on 6inu3
6n 5ni%GBinu%+ .ersions of Selenium before F-8 needed to in.o'e Dfirefo%,binE directly+ so if you are using a pre.ious .ersion+ ma'e sure
that the real e%ecutable is on the path-
6n most Binu% distributions+ the real firefo%:bin is located on1
/usr/lib/!ire!o"-"+"+"/
Where the %-%-% is the .ersion number you currently ha.e- So+ to add that path to the users path- you #ill ha.e to add the follo#ing to
your -bashrc file1
e"port &:TL)*Z&:TL?/usr/lib/!ire!o"-"+"+"/*
If necessary+ you can specify the path to firefo%,bin directly in your test+ li'e this1
*@!ire!o" /usr/lib/!ire!o"-"+"+"/!ire!o"-bin*
I, and Style Attributes
If you are running your tests on Internet &%plorer and you cannot locate elements using their style attribute- $or e%ample1
//td68style)*bac<ground-color?yellow*7
This #ould #or' perfectly in $irefo%+ 6pera or Safari but not #ith I&- I& interprets the 'eys in Jstyle as uppercase- So+ e.en if the source
code is in lo#ercase+ you should use1
//td68style)*O:CXWI(JQD-C(,(I?yellow*7
This is a problem if your test is intended to #or' on multiple bro#sers+ but you can easily code your test to detect the situation and try the
alternati.e locator that only #or's in I&-
,rror encountered - BCannot con'ert ob!ect to primiti'e 'alueC 0ith shut do0n of 9googlechrome bro0ser
To a.oid this error you ha.e to start bro#ser #ith an option that disables same origin policy chec's1
selenium+start(*command,ine%lags)--disable-web-security*)R
Where can I As% Wuestions that Aren"t Ans0ered Here?
Try our user group
Table Of Contents
Test (esign !onsiderations
Introducing Test (esign
Types of Tests
3alidating 2esults
Bocation Strategies
Wrapping Selenium !alls
5I *apping
Page 6bject (esign Pattern
(ata (ri.en Testing
(atabase 3alidation
Test +esign Considerations
Introducing Test +esign
We.e pro.ided in this chapter information that #ill be useful to both those ne# to test automation and for the e%perienced 4A professional-
Here #e describe the most common types of automated tests- We also describe ?design patterns commonly used in test automation for
impro.ing the maintenance and e%tensibily of your automation suite- The more e%perienced reader #ill find these interesting if not already
using these techni0ues-
Types of Tests
What parts of your application should you test? That depends on aspects of your project1 user e%pectations+ time allo#ed for the project+
priorities set by the project manager and so on- 6nce the project boundaries are defined though+ you+ the tester+ #ill certainly ma'e many
decisions on #hat to test-
We.e created a fe# terms here for the purpose of categori/ing the types of test you may perform on your #eb application- These terms are
by no means standard+ although the concepts #e present here are typical for #eb,application testing-
Testing Static Content
The simplest type of test+ a content test+ is a simple test for the e%istence of a static+ non,changing+ 5I element- $or instance
(oes each page ha.e its e%pected page title? This can be used to .erify your test found an e%pected page after follo#ing a lin'-
(oes the applications home page contain an image e%pected to be at the top of the page?
(oes each page of the #ebsite contain a footer area #ith lin's to the company contact page+ pri.acy policy+ and trademar's
information?
(oes each page begin #ith heading te%t using the UhFQ tag? And+ does each page ha.e the correct te%t #ithin that header?
"ou may or may not need content tests- If your page content is not li'ely to be affected then it may be more efficient to test page content
manually- If+ for e%ample+ your application in.ol.es files being mo.ed to different locations+ content tests may pro.e .aluable-
Testing 6in%s
A fre0uent source of errors for #eb,sites is bro'en lin's or missing pages behind lin's- Testing in.ol.es clic'ing each lin' and .erifying the
e%pected page- If static lin's are infre0uently changed then manual testing may be sufficient- Ho#e.er if your #eb designers fre0uently alter
lin's+ or if files are occasionally relocated+ lin' tests should be automated-
2unction Tests
These #ould be tests of a specific function #ithin your application+ re0uiring some type of user input+ and returning some type of results-
6ften a function test #ill in.ol.e multiple pages #ith a form,based input page containing a collection of input fields+ Submit and !ancel
operations+ and one or more response pages- 5ser input can be .ia te%t,input fields+ chec' bo%es+ drop,do#n lists+ or any other bro#ser,
supported input-
$unction tests are often the most comple% tests youll automate+ but are usually the most important- Typical tests can be for login+
registration to the site+ user account operations+ account settings changes+ comple% data retrie.al operations+ among others- $unction tests
typically mirror the user,scenarios used to specify the features and design or your application-
Testing +ynamic ,lements
6ften a #eb page element has a uni0ue identifier used to uni0uely locate that element #ithin the page- 5sually these are implemented using
the html tags ?id attribute or its ?name attribute- These names can be a static+ i-e unchanging+ string constant- They can also be dynamically
generated .alues that .ary each instance of the page- $or e%ample+ some #eb ser.ers might name a displayed document docK@=F one
instance of a page+ and ?doc=F9@ on a different instance of the page depending on #hat ?document the user #as retrie.ing- A test script
.erifying that a document e%ists may not ha.e a consistent identifier to use for locating that document- 6ften+ dynamic elements #ith
.arying identifiers are on some type of result page based on a user action- This though certainly depends on the function of the #eb
application-
Heres an e%ample-
<input type)*chec<bo"* alue)*true* id)*add%orm?SPD2/?SPD20?5?SPD24?5?
chec<Oo"*/>
This sho#s an HT*B tag for a chec' bo%- Its I( ;add$orm1\I(I91\I(IL181\I(IC181chec'Bo%< is a dynamically generated .alue- The ne%t
time the same page is opened it #ill li'ely be a different .alue-
A!a3 Tests
Aja% is a technology #hich supports dynamically changing user interface elements #hich can dynamically change #ithout the bro#ser
ha.ing to reload the page+ such as animation+ 2SS feeds+ and real,time data updates among others- Theres a countless #ays Aja% can be
used to update elements on a #eb page- But+ the easy #ay to thin' of this is that in Aja%,dri.en applications+ data can retrie.ed from the
application ser.er and then displayed on the page #ithout reloading the entire page- 6nly a portion of the page+ or strictly the element itself
is reloaded-
Aalidating *esults
Assert 's& Aerify
When should you use an assert command and #hen should you use a .erify command? This is up to you- The difference is in #hat you #ant
to happen #hen the chec' fails- (o you #ant your test to terminate+ or to continue and simply record that the chec' failed?
Heres the trade,off- If you use an assert+ the test #ill stop at that point and not run any subse0uent chec's- Sometimes+ perhaps often+ that is
#hat you #ant- If the test fails you #ill immediately 'no# the test did not pass- Test engines such as TestN> and :5nit ha.e plugins for
commonly used de.elopment en.ironments ;!hap L< #hich con.eniently flag these tests as failed tests- The ad.antage1 you ha.e an
immediate .isual of #hether the chec's passed- The disad.antage1 #hen a chec' does fail+ there are other chec's #hich #ere ne.er
performed+ so you ha.e no information on their status-
In contrast+ .erify commands #ill not terminate the test- If your test uses only .erify commands you are guaranteed ;assuming no
une%pected e%ceptions< the test #ill run to completion #hether the chec's find defects or not- The disad.antage1 you ha.e to do more #or'
to e%amine your test results- That is+ you #ont get feedbac' from TestN> or :5nit- "ou #ill need to loo' at the results of a console printout
or a log output- And you #ill need to ta'e the time to loo' through this output e.ery time you run your test- If you are running hundreds of
tests+ each #ith its o#n log+ this #ill be time,consuming+ and the immediate feedbac' of asserts #ill be more appropriate- Asserts are more
commonly used than .erifys due to their immediate feedbac'-
Trade-offsK assertTextPresent5 assertElementPresent5 assertText
"ou should no# be familiar #ith these commands+ and the mechanics of using them- If not+ please refer to !hapter K first- When
constructing your tests+ you #ill need to decide
(o I only chec' that the te%t e%ists on the page? ;verify6asserte%t&resent<
(o I only chec' that the HT*B element e%ists on the page? That is+ the te%t+ image+ or other content is not to be chec'ed+ only the
HT*B tag is #hat is rele.ant- ;verify6assert'lement&resent<
*ust I test both+ the element and its te%t content? ;verify6asserte%t<
There is no right ans#er- It depends on the re0uirements for your test- Which+ of course+ depend on the re0uirements for the application
youre testing- If in doubt+ use asserte%t since this is the strictest type of chec'point- "ou can al#ays change it later but at least you #ont be
missing any potential failures-
5erify6asserte%t is the most specific test type- This can fail if either the HT*B element ;tag< 62 the te%t is not #hat your test is e%pecting-
Perhaps your #eb,designers are fre0uently changing the page and you dont #ant your test to fail e.ery time they do this because the
changes themsel.es are e%pected periodically- Ho#e.er+ assume you still need to chec' that something is on the page+ say a paragraph+ or
heading te%t+ or an image- In this case you can use verify6assert'lement&resent- It #ill ensure that a particular type of element e%ists ;and if
using OPath can ensure it e%ists relati.e to other objects #ithin the page<- But you dont care #hat the content is- "ou only care that a
specific element+ say+ an image+ is at a specific location-
>etting a feel for these types of decisions #ill come #ith time and a little e%perience- They are easy concepts+ and easy to change in your
test-
6ocation Strategies
Choosing a 6ocation Strategy
There are multiple #ays of selecting an object on a page- But #hat are the trade offs of each of these locator types? 2ecall #e can locate an
object using
the elements I(
the elements name attribute
an OPath statement
by a lin's te%t
document object model ;(6*<
5sing an element I( or name locator is the most efficient in terms of test performance+ and also ma'es your test code more readable+
assuming the I( or name #ithin the page source is #ell,named- OPath statements ta'e longer to process since the bro#ser must run its
OPath processor- OPath has been 'no#n to be especially slo# in Internet &%plorer .ersion I- Bocating .ia a lin's te%t is often con.enient
and performs #ell- This techni0ue is specific to lin's though- Also+ if the lin' te%t is li'ely to change fre0uently+ locating by the UaQ element
#ould be the better choice-
Sometimes though+ you must use an OPath locator- If the page source does not ha.e an I( or name attribute you may ha.e no choice but to
use an OPath locator- ;(6* locators are no longer commonly used since OPath can do e.erything they can and more- (6* locators are
a.ailable simply to support legacy tests-<
There is an ad.antage to using OPath that locating .ia I( or name attributes do not ha.e- With OPath ;and (6*< you can locate an object
#ith respect to another object on the page- $or e%ample+ if there is a lin' that must occur #ithin the second paragraph #ithin a Udi.Q section+
you can use OPath to specify this- With I( and name locators+ you can only specify that they occur on the page that is+ some#here on the
page- If you must test that an image displaying the company logo appears at the top of the page #ithin a header section OPath may be the
better locator-
6ocating +ynamic ,lements
As #as described earlier in the section on types of tests+ a dynamic element is a page element #hose identifer .aries #ith each instance of
the page- $or e%ample+
<a class)*button* id)*adminLome%orm* onclic<)*return oam$ubmit%orm(9adminLome%orm9E
9adminLome%orm?SPD.39)R* hre!)*>*>View :rchied :llocation -ents</a>
This HT*B anchor tag defines a button #ith an I( attribute of DadminHome$ormE- Its a fairly comple% anchor tag #hen compared to most
HT*B tags+ but it is still a static tag- The HT*B #ill be the same each time this page is loaded in the bro#ser- Its I( remains constant #ith
all instances of this page- That is+ #hen this page is displayed+ this 5I element #ill al#ays ha.e this Identifier- So+ for your test script to clic'
this button you simply need to use the follo#ing selenium command-
clic< adminLome%orm
6r+ in Selenium F-8
selenium+clic<(*adminLome%orm*)R
"our application+ ho#e.er+ may generate HT*B dynamically #here the identifier .aries on different instances of the #ebpage- $or instance+
HT*B for a dynamic page element might loo' li'e this-
<input type)*chec<bo"* alue)*true* id)*add%orm?SPD2/?SPD20?5?SPD24?5?chec<Oo"*
name)*add%orm?SPD2/?SPD20?5?SPD24?5?chec<Oo"*/>
This defines a chec'bo%- Its I( and name attributes ;both add$orm1\I(I91\I(IL181\I(IC181chec'Bo%< are dynamically generated .alues- In
this case+ using a standard locator #ould loo' something li'e the follo#ing-
clic< add%orm?SPD2/?SPD20?5?SPD24?5?chec<Oo"
6r+ again in Selenium,2!
selenium+clic<(*add%orm?SPD2/?SPD20?5?SPD24?5?chec<Oo"*)R
>i.en the dynamically generated Identifier+ this approach #ould not #or'- The ne%t time this page is loaded the Identifier #ill be a different
.alue from the one used in the Selenium command and therefore+ #ill not be found- The clic' operation #ill fail #ith an Delement not foundE
error-
To correct this+ a simple solution #ould be to just use an OPath locator rather than trying to use an I( locator- So+ for the chec'bo% you can
simply use
clic< //input
6r+ if it is not the first input element on the page ;#hich it li'ely is not< try a more detailed OPath statement-
clic< //input6.7
6r
clic< //di/p6#7/input6.7
If ho#e.er+ you do need to use the I( to locate the element+ a different solution is needed- "ou can capture this I( from the #ebsite before
you use it in a Selenium command- It can be done li'e this-
$tring67 chec<bo"ids ) selenium+get:ll%ields()R // Collect all input PDs on page+
!or($tring chec<bo"id?chec<bo"ids) D
i!(chec<bo"id+contains(*add%orm*)) D
selenium+clic<(chec<bo"id)R
F
F
This approach #ill #or' if there is only one chec' bo% #hose I( contains the te%t ?add$orm-
6ocating A!a3 ,lements
As #as presented in the Test Types subsection abo.e+ a page element implemented #ith Aja% is an element that can be dynamically refreshed
#ithout ha.ing to refresh the entire page- The best #ay to locate and .erify an Aja% element is to use the Selenium 7-8 Web(ri.er API- It
#as specifically designed to address testing of Aja% elements #here Selenium F has some limitations-
In Selenim 7-8 you use the #ait$or;< method to #ait for a page element to become a.ailable- The parameter is a By object #hich is ho#
Web(ri.er implements locators- This is e%plained in detail in the Web(ri.er chapters-
To do this #ith Selenium F-8 ;Selenium,2!< a bit more coding is in.ol.ed+ but it isnt difficult- The approach is to chec' for the element+ if
its not a.ailable #ait for a predefined period and then again rechec' it- This is then e%ecuted #ith a loop #ith a predetermined time,out
terminating the loop if the element isnt found-
Bets consider a page #hich brings a lin' ;lin'Taja%Bin'< on clic' of a button on page ;#ithout refreshing the page< This could be handled
by Selenium using a for loop-
// ,oop initialiAation+
!or (int second ) 5RR secondCC) D
// P! loop is reached 15 seconds then brea< the loop+
i! (second >) 15) brea<R
// $earch !or element *lin<)aKa",in<* and i! aailable then brea< loop+
try D i! (selenium+is-lement&resent(*lin<)aKa",in<*)) brea<R F catch (-"ception e) DF
// &ause !or ' second+
Thread+sleep('555)R
F
This certainly isnt the only solution- Aja% is a common topic in the user forum and #e recommend searching pre.ious discussions to see
#hat others ha.e done-
Wrapping Selenium Calls
As #ith any programming+ you #ill #ant to use utility functions to handle code that #ould other#ise be duplicated throughout your tests-
6ne #ay to pre.ent this is to #rap fre0uently used selenium calls #ith functions or class methods of your o#n design- $or e%ample+ many
tests #ill fre0uently clic' on a page element and #ait for page to load multiple times #ithin a test-
selenium+clic<(element,ocator)R
selenium+wait%or&ageTo,oad(wait&eriod)R
Instead of duplicating this code you could #rite a #rapper method that performs both functions-
/@@
@ Clic<s and Taits !or page to load+
@
@ param element,ocator
@ param wait&eriod
@/
public oid clic<:ndTait($tring element,ocatorE $tring wait&eriod) D
selenium+clic<(element,ocator)R
selenium+wait%or&ageTo,oad(wait&eriod)R
F
QSafe Operations" for ,lement resence
Another common usage of #rapping Selenium methods is to chec' for presence of an element on page before carrying out some operation-
This is sometimes called a ?safe operation- $or instance+ the follo#ing method could be used to implement a safe operation that depends on
an e%pected element being present-
/@@
@ $elenum-IC -- Clic<s on element only i! it is aailable on page+
@
@ param element,ocator
@/
public oid sa!eClic<($tring element,ocator) D
i!(selenium+is-lement&resent(element,ocator)) D
selenium+clic<(element,ocator)R
F else D
// Jsing the TestQW :&P !or logging
Ieporter+log(*-lement? * Celement,ocatorC *E is not aailable on page - *
Cselenium+get,ocation())R
F
F
This e%ample uses the Selenium F API but Selenium 7 also supports this-
/@@
@ $elenium-TebDrier -- Clic<s on element only i! it is aailable on page+
@
@ param element,ocator
@/
public oid sa!eClic<($tring element,ocator) D
Teb-lement web-lement ) getDrier()+!ind-lement(Oy+VVVV(element,ocator))R
i!(web-lement !) null) D
selenium+clic<(element,ocator)R
F else D
// Jsing the TestQW :&P !or logging
Ieporter+log(*-lement? * Celement,ocatorC *E is not aailable on page - *
C getDrier()+getJrl())R
F
F
In this second e%ample ?OOOO is simply a placeholder for one of the multiple location methods that can be called here-
5sing safe methods is up to the test de.elopers discretion- Hence+ if test e%ecution is to be continued+ e.en in the #a'e of missing elements
on the page+ then safe methods could be used+ #hile posting a message to a log about the missing element- This+ essentially+ implements a
?.erify #ith a reporting mechanism as opposed to an aborti.e assert- But if element must be a.ailable on page in order to be able to carry
out further operations ;i-e- login button on home page of a portal< then this safe method techni0ue should not be used-
@I 7apping
A 5I map is a mechanism that stores all the locators for a test suite in one place for easy modification #hen identifiers or paths to 5I
elements change in the A5T- The test script then uses the 5I *ap for locating the elements to be tested- Basically+ a 5I map is a repository
of test script objects that correspond to 5I elements of the application being tested-
What ma'es a 5I map helpful? Its primary purpose is ma'ing test script management much easier- When a locator needs to be edited+ there
is a central location for easily finding that object+ rather than ha.ing to search through test script code- Also+ it allo#s changing the Identifier
in a single place+ rather than ha.ing to ma'e the change in multiple places #ithin a test script+ or for that matter+ in multiple test scripts-
To summari/e+ a 5I map has t#o significant ad.antages-
5sing a centrali/ed location for 5I objects instead of ha.ing them scattered throughout the script- This ma'es script maintenance
more efficient-
!ryptic HT*B Identifiers and names can be gi.en more human,readable names impro.ing the readability of test scripts-
!onsider the follo#ing+ difficult to understand+ e%ample ;in ja.a<-
public oid testQew() throws -"ception D
selenium+open(*http?//www+test+com*)R
selenium+type(*login%orm?tbJsername*E *""""""""*)R
selenium+clic<(*login%orm?btn,ogin*)R
selenium+clic<(*adminLome%orm?Sactiitynew*)R
selenium+wait%or&ageTo,oad(*.5555*)R
selenium+clic<(*add-dit-ent%orm?SPDcancel*)R
selenium+wait%or&ageTo,oad(*.5555*)R
selenium+clic<(*adminLome%orm?Sactiityold*)R
selenium+wait%or&ageTo,oad(*.5555*)R
F
This script #ould be hard to follo# for anyone not familiar #ith the A5Ts page source- &.en regular users of the application might ha.e
difficulty understanding #hat thus script does- A better script could be1
public oid testQew() throws -"ception D
selenium+open(*http?//www+test+com*)R
selenium+type(admin+usernameE *""""""""*)R
selenium+clic<(admin+loginbutton)R
selenium+clic<(admin+eents+createneweent)R
selenium+wait%or&ageTo,oad(*.5555*)R
selenium+clic<(admin+eents+cancel)R
selenium+wait%or&ageTo,oad(*.5555*)R
selenium+clic<(admin+eents+iewoldeents)R
selenium+wait%or&ageTo,oad(*.5555*)R
F
No#+ using some comments and #hitespace along #ith the 5I *ap identifiers ma'es a .ery readable script-
public oid testQew() throws -"ception D
// (pen app url+
selenium+open(*http?//www+test+com*)R
// &roide admin username+
selenium+type(admin+usernameE *""""""""*)R
// Clic< on ,ogin button+
selenium+clic<(admin+loginbutton)R
// Clic< on Create Qew -ent button+
selenium+clic<(admin+eents+createneweent)R
selenium+wait%or&ageTo,oad(*.5555*)R
// Clic< on Cancel button+
selenium+clic<(admin+eents+cancel)R
selenium+wait%or&ageTo,oad(*.5555*)R
// Clic< on View (ld -ents button+
selenium+clic<(admin+eents+iewoldeents)R
selenium+wait%or&ageTo,oad(*.5555*)R
F
There are .arious #ays a 5I *ap can be implemented- 6ne could create a class or struct #hich only stores public String .ariables each
storing a locator- Alternati.ely+ a te%t file storing 'ey .alue pairs could be used- In :a.a+ a properties file containing 'eyG.alue pairs is
probably best method-
!onsider a property file prop.properties #hich assigns as ?aliases reader,friendly identifiers for 5I elements from the pre.ious e%ample-
admin+username ) login%orm?tbJsername
admin+loginbutton ) login%orm?btn,ogin
admin+eents+createneweent ) adminLome%orm?Sactiitynew
admin+eents+cancel ) add-dit-ent%orm?SPDcancel
admin+eents+iewoldeents ) adminLome%orm?Sactiityold
The locators #ill still refer to html objects+ but #e ha.e introduced a layer of abstraction bet#een the test script and the 5I elements- 3alues
are read from the properties file and used in the Test !lass to implement the 5I *ap- $or more on :a.a properties files refer to the follo#ing
lin'-
age Ob!ect +esign attern
Page 6bject is a (esign Pattern #hich has become popular in test automation for enhancing test maintenance and reducing code duplication-
A page object is an object,oriented class that ser.es as an interface to a page of your A5T- The tests then use the methods of this page object
class #hene.er they need to interact #ith that page of the 5I- The benefit is that if the 5I changes for the page+ the tests themsel.es dont
need to change+ only the code #ithin the page object needs to change- Subse0uently all changes to support that ne# 5I are located in one
place-
The Page 6bject (esign Pattern pro.ides the follo#ing ad.antages-
F- There is clean separation bet#een test code and page specific code such as locators ;or their use if youre using a 5I map< and layout-
7- There is single repository for the ser.ices or operations offered by the page rather than ha.ing these ser.ices scattered through out the
tests-
In both cases this allo#s any modifications re0uired due to 5I changes to all be made in one place- 5seful information on this techni0ue can
be found on numerous blogs as this ?test design pattern is becoming #idely used- $e encourage the reader who wishes to know more to
search the internet for blogs on this subEect. *any ha.e #ritten on this design pattern and can pro.ide useful tips beyond the scope of this
user guide- To get you started+ though+ #ell illustrate page objects #ith a simple e%ample-
$irst+ consider an e%ample+ typical of test automation+ that does not use a page object-
/@@@
@ Tests login !eature
@/
public class ,ogin D
public oid test,ogin() D
selenium+type(*inputOo"*E *testJser*)R
selenium+type(*password*E *my supersecret password*)R
selenium+clic<(*sign-in*)R
selenium+wait%or&ageTo,oad(*&ageTait&eriod*)R
:ssert+assertTrue(selenium+is-lement&resent(*compose button*)E
*,ogin was unsuccess!ul*)R
F
F
There are t#o problems #ith this approach-
F- There is no separation bet#een the test method and the A5Ts locators ;I(s in this e%ample<P both are intert#ined in a single method-
If the A5Ts 5I changes its identifiers+ layout+ or ho# a login is input and processed+ the test itself must change-
7- The id,locators #ould be spread in multiple tests+ all tests that had to use this login page-
Applying the page object techni0ues this e%ample could be re#ritten li'e this in the follo#ing e%ample of a page object for a Sign,in page-
/@@
@ &age (bKect encapsulates the $ign-in page+
@/
public class $ignPn&age D
priate $elenium seleniumR
public $ignPn&age($elenium selenium) D
this+selenium ) seleniumR
i!(!selenium+getTitle()+e=uals(*$ign in page*)) D
throw new Pllegal$tate-"ception(*This is not sign in pageE current page is? *
Cselenium+get,ocation())R
F
F
/@@
@ ,ogin as alid user
@
@ 8param userQame
@ 8param password
@ 8return Lome&age obKect
@/
public Lome&age loginValidJser($tring userQameE $tring password) D
selenium+type(*username!ield*E userQame)R
selenium+type(*password!ield*E password)R
selenium+clic<(*sign-in*)R
selenium+wait%or&ageTo,oad(*wait&eriod*)R
return new Lome&age(selenium)R
F
F
and page object for a Home page could loo' li'e this-
/@@
@ &age (bKect encapsulates the Lome &age
@/
public class Lome&age D
priate $elenium seleniumR
public Lome&age($elenium selenium) D
i! (!selenium+getTitle()+e=uals(*Lome &age o! logged in user*)) D
throw new Pllegal$tate-"ception(*This is not Lome &age o! logged in userE current page*
C
*is? * Cselenium+get,ocation())R
F
F
public Lome&age manage&ro!ile() D
// &age encapsulation to manage pro!ile !unctionality
return new Lome&age(selenium)R
F
/@Nore methods o!!ering the serices represented by Lome &age
o! ,ogged Jser+ These methods in turn might return more &age (bKects
!or e"ample clic< on Compose mail button could return ComposeNail class obKect@/
F
So no#+ the login test #ould use these t#o page objects as follo#s-
/@@@
@ Tests login !eature
@/
public class Test,ogin D
public oid test,ogin() D
$ignPn&age signPn&age ) new $ignPn&age(selenium)R
Lome&age home&age ) signPn&age+loginValidJser(*userQame*E *password*)R
:ssert+assertTrue(selenium+is-lement&resent(*compose button*)E
*,ogin was unsuccess!ul*)R
F
F
There is a lot of fle%ibility in ho# the page objects may be designed+ but there are a fe# basic rules for getting the desired maintainability of
your test code- Page objects themsel.es should ne.er be ma'e .erifications or assertions- This is part of your test and should al#ays be
#ithin the tests code+ ne.er in an page object- The page object #ill contain the representation of the page+ and the ser.ices the page pro.ides
.ia methods but no code related to #hat is being tested should be #ithin the page object-
There is one+ single+ .erification #hich can+ and should+ be #ithin the page object and that is to .erify that the page+ and possibly critical
elements on the page+ #ere loaded correctly- This .erification should be done #hile instantiating the page object- In the e%amples abo.e+
both the SignInPage and HomePage constructors chec' that the e%pected page is a.ailable and ready for re0uests from the test-
A page object does not necessarily need to represent an entire page- The Page 6bject design pattern could be used to represent components
on a page- If a page in the A5T has multiple components+ it may impro.ed maintainability if there #as a separate page object for each
component-
There are other design patterns that also may be used in testing- Some use a Page $actory for instantiating their page objects- (iscussing all
of these is beyond the scope of this user guide- Here+ #e merely #ant to introduce the concepts to ma'e the reader a#are of some of the
things that can be done- As #as mentioned earlier+ many ha.e blogged on this topic and #e encourage the reader to search for blogs on these
topics-
+ata +ri'en Testing
(ata (ri.en Testing refers to using the same test ;or tests< multiple times #ith .arying data- These data sets are often from e%ternal files
i-e- -cs. file+ te%t file+ or perhaps loaded from a database- (ata dri.en testing is a commonly used test automation techni0ue used to .alidate
an application against many .arying input- When the test is designed for .arying data+ the input data can e%pand+ essentially creating
additional tests+ #ithout re0uiring changes to the test code-
In ythonK
The Python script abo.e opens a te%t file- This file contains a different search string on each line- The code then sa.es this in an array of
strings+ and iterates o.er the array doing a search and assert on each string-
This is a .ery basic e%ample+ but the idea is to sho# that running a test #ith .arying data can be done easily #ith a programming or scripting
language- $or more e%amples+ refer to the Selenium 2! #i'i for e%amples of reading data from a spreadsheet or for using the data pro.ider
capabilities of TestN>- Additionally+ this is a #ell,'no#n topic among test automation professionals including those #ho dont use Selenium
so searching the internet on Ddata,dri.en testingE should re.eal many blogs on this topic-
+atabase Aalidation
Another common type of testing is to compare data in the 5I against the data actually stored in the A5Ts database- Since you can also do
database 0ueries from a programming language+ assuming you ha.e database support functions+ you can use them to retrie.e data and then
use the data to .erify #hats displayed by the A5T is correct-
!onsider the e%ample of a registered email address to be retrie.ed from a database and then later compared against the 5I- An e%ample of
establishing a (B connection and retrie.ing data from the (B could loo' li'e this-
In Da'aK
// ,oad Nicroso!t $U, $erer YDOC drier+
Class+!orQame(*com+microso!t+s=lserer+Kdbc+$U,$ererDrier*)R
// &repare connection url+
$tring url ) *Kdbc?s=lserer?//'4#+'13+'+'35?'/..RDatabaseQame)T-$TSDO*R
// Wet connection to DO+
public static Connection con )
DrierNanager+getConnection(urlE *username*E *password*)R
// Create statement obKect which would be used in writing DD, and DN,
// $U, statement+
public static $tatement stmt ) con+create$tatement()R
// $end $U, $-,-CT statements to the database ia the $tatement+e"ecuteUuery
// method which returns the re=uested in!ormation as rows o! data in a
// Iesult$et obKect+
Iesult$et result ) stmt+e"ecuteUuery
(*select top ' emailSaddress !rom userSregisterStable*)R
// %etch alue o! *emailSaddress* !rom *result* obKect+
$tring emailaddress ) result+get$tring(*emailSaddress*)R
// Jse the email:ddress alue to login to application+
selenium+type(*userPD*E emailaddress)R
selenium+type(*password*E secret&assword)R
selenium+clic<(*loginOutton*)R
selenium+wait%or&ageTo,oad(time(ut)R
:ssert+assertTrue(selenium+isTe"t&resent(*Telcome bac<* Cemailaddress)E *Jnable to log in !or user*
Cemailaddress)
This is a simple :a.a e%ample of data retrie.al from a database-
Table Of Contents
Selenium,>rid
4uic' Start
What is Selenium,>rid?
When to 5se It
Selenium,>rid 7-8
Selenium,>rid F-8
Ho# Selenium,>rid Wor's)With a Hub and Nodes
Installation
Starting Selenium,>rid
!onfiguring Selenium,>rid
Hub !onfiguration
Node !onfiguration
Timing Parameters
>etting !ommand,Bine Help
!ommon &rrors
Troubleshooting
Selenium-.rid
Note: $e are currently working on this chapter. &resently we have introductory info here for people completely new to "elnium:9rid. -ver
the ne%t few months we hope to provide useful e%amples and illustrations to thoroughly e%plain how to use "elenium:9rid.
Wuic% Start
If youre already e%perienced in Selenium test automation you may simply need a 0uic',start to get up and running- This chapter has much
information geared to many s'ill le.els+ but may be too much if youre loo'ing for just a 0uic' reference to 0uic'ly try things out- $or a
0uic',start+ refer to the Selenium,>rid articles in the Selenium Wi'i-
What is Selenium-.rid?
Selenium,>rid allo#s you run your tests on different machines against different bro#sers in parallel- That is+ running multiple tests at the
same time against different machines running different bro#sers and operating systems- &ssentially+ Selenium,>rid support distributed test
e%ecution- It allo#s for running your tests in a distributed test e%ecution en.ironment-
When to @se It
>enerally spea'ing+ theres t#o reasons #hy you might #ant to use Selenium,>rid-
To run your tests against multiple bro#sers+ multiple .ersions of bro#ser+ and bro#sers running on different operating systems-
To reduce the time it ta'es for the test suite to complete a test pass-
Selenium,>rid is used to speed up the e%ecution of a test pass by using multiple machines to run tests in parallel- $or e%ample+ if you ha.e a
suite of F88 tests+ but you set up Selenium,>rid to support 9 different machines ;3*s or separate physical machines< to run those tests+ your
test suite #ill complete in ;roughly< one,fourth the time as it #ould if you ran your tests se0uentially on a single machine- $or large test
suites+ and long,running test suite such as those performing large amounts of data,.alidation+ this can be a significant time,sa.er- Some test
suites can ta'e hours to run- Another reason to boost the time spent running the suite is to shorten the turnaround time for test results after
de.elopers chec',in code for the A5T- Increasingly soft#are teams practicing Agile soft#are de.elopment #ant test feedbac' as
immediately as possible as opposed to #ait o.ernight for an o.ernight test pass-
Selenium,>rid is also used to support running tests against multiple runtime en.ironments+ specifically+ against different bro#sers at the
same time- $or e%ample+ a ?grid of .irtual machines can be setup #ith each supporting a different bro#ser that the application to be tested
must support- So+ machine F has Internet &%plorer @+ machine 7+ Internet &%plorer C+ machine K the latest !hrome+ and machine 9 the latest
$irefo%- When the test suite is run+ Selenium,>rid recei.es each test,bro#ser combination and assigs each test to run against its re0uired
bro#ser-
In addition+ one can ha.e a grid of all the same bro#ser+ type and .ersion- $or instance+ one could ha.e a grid of 9 machines each running K
instances of $irefo% F7+ allo#ing for a ?ser.er,farm ;in a sense< of a.ailable $irefo% instances- When the suite runs+ each test is passed to
Selenium,>rid #hich assigns the test to the ne%t a.ailable $irefo% instance- In this manner one gets test pass #here concei.ably F7 tests are
all running at the same time in parallel+ significantly reducing the time re0uired to complete a test pass-
Selenium,>rid is .ery fle%ible- These t#o e%amples can be combined to allo# multiple instances of each bro#ser type and .ersion- A
configuration such as this #ould pro.ide both+ parallel e%ecution for fast test pass completion and support for multiple bro#ser types and
.ersions simultaneously-
Selenium-.rid #&1
Selenium,>rid 7-8 is the latest release as of the #riting of this document ;LG7=G78F7<- It is 0uite different from .ersion F of Selenium,>rid-
In 7-8 Selenium,>rid #as merged #ith the Selenium,2! ser.er- No#+ you only need to do#nload a single -jar file to get the remote
Selenium,2!,Ser.er and Selenium,>rid all in one pac'age-
Selenium-.rid )&1
3ersion F #as the first general release of Selenium,>rid- If you are ne# to Selenium,>rid you should use .ersion 7- Its been updated and
has ne# features+ and supports Selenium,Web(ri.er- Begacy test systems may still be using .ersion F ho#e.er- Information on Selenium,
>rid .ersion F may be found at the Selenium,>rid #ebsite-
Ho0 Selenium-.rid Wor%s>With a Hub and Nodes
A grid consists of a single hub+ and one or more nodes- Both are started using the selenium,ser.er-jar e%ecutable- We.e listed some
e%amples in the follo#ing sections of this chapter-
The hub recei.es a test to be e%ecuted along #ith information on #hich bro#ser and ?platform ;i-e- WIN(6WS+ BIN5O+ etc< #here the test
should be run- It ?'no#s the configuration of each node that has been ?registered to the hub- 5sing this information it selects an a.ailable
node that has the re0uested bro#ser,platform combination- 6nce a node has been selected+ Selenium commands initiated by the test are send
the the hub+ #hich passes them to the node assigned to that test- The node runs the bro#ser+ and e%ecutes the Selenium commands #ithin
that bro#ser against the application under test-
A diagram illustrates this- 2efer to the second diagram on this page ;the first one is illustrating Selenium,2!<- The second diagram #as for
Selenium,>rid F+ ho#e.er it still applies and is a good illustration of #hat #ere describing here- The only difference is one of terminology-
2eplace the term ?Selenium 2emote !ontrol #ith ?Selenium,>rid node the diagram #ill match our description for Selenium,>rid 7-
Installation
Installation is simple- (o#nload the Selenium,Ser.er jar file from the SeleniumH0 #ebsites do#nload page- "ou #ant the lin' under the
section DSelenium,Ser.er ;formerly Selenium,2!<E-
Install it in a folder of your choice- "oull need to be sure the ja.a e%ecutable is on your e%ecution path so you can run it from the command,
line- If it does not run correcly+ .erify your systems path .ariable includes the path to the ja.a-e%e-
Starting Selenium-.rid
>enerally you #ould start a hub first since nodes depend on a hub- This is not abolutely necessary ho#e.er+ since nodes can recogni/e #hen
a hub has been started and .ice,.ersa- $or learning purposes though+ it #ould easier to start the hub first+ other#ise youll see error messages
that may not #ant to start off #ith your first time using Selenium,>rid-
Starting a Hub
To start a hub #ith default parameters+ run the follo#ing command from a command,line shell- This #ill #or' on all the supported
platforms+ Windo#s Binu%+ or *ac6s-
Kaa -Kar selenium-serer-standalone-#+#'+5+Kar -role hub
This starts a hub using default parameter .alues- Well e%plain these parameters in folo#ing subsections- Note that you #ill li'ely ha.e to
change the .ersion number in the jar filename depending on #hich .ersion of the selenium,ser.er youre using-
Starting a Node
To start a node using default parameters+ run the follo#ing command from a command,line-
Kaa -Kar selenium-serer-standalone-#+#'+5+Kar -role node -hub http?//localhost?/////grid/register
This assumes the hub has been started abo.e using default parameters- The default port the hub uses to listen for ne# re0uests is port 9999-
This is #hy port 9999 #as used in the 52B for locating the hub- Also the use of ?localhost assumes your node is running on the same
machine as your hub- $or getting started this is probably easiest- If running the hub and node on separate machines+ simply replace
?localhost #ith the hostname of the remote machine running the hub-
WA2NIN>1 Be sure to turn off the fire#alls on the machine running your hub and nodes- 6ther#ise you may get connection errors-
Configuring Selenium-.rid
+efault Configuration
DSON Configuration 2ile
Configuring Aia the Command-6ine Options
Hub Configuration
To run the hub using the default options simply specify ,role hub to the Selenim,Ser.er
Kaa -Kar selenium-serer-standalone-#+#'+5+Kar -hub
"ou should see the follo#ing logging output-
Yul '4E #5'# '5?/1?#' :N org+open=a+grid+selenium+Wrid,auncher main
PQ%(? ,aunching a selenium grid serer
#5'#-52-'4 '5?/1?#0+53#?PQ%(?osKs+$erer?Ketty-2+"+y-$Q:&$L(T
#5'#-52-'4 '5?/1?#0+'0'?PQ%(?osKsh+Conte"tLandler?started o+s+K+s+$erletConte"tLandlerD/EnullF
#5'#-52-'4 '5?/1?#0+'30?PQ%(?osKs+:bstractConnector?$tarted $oc<etConnector85+5+5+5?////
Specifying the ort
The default port used by the hub is 9999- The port being referred to hear+ is the T!PGIP port used #hen the ?client+ that is+ the automated
tests connect to the Selenium,>rid hub- If another application on your computer is already using this port+ or if+ you already ha.e a
Selenium,Ser.er started+ youll see the follo#ing message in the log output-
'5?01?.0+/45 T:IQ - %ailed to start? $oc<et,istener585+5+5+5?////
-"ception in thread *main* Kaa+net+Oind-"ception? $elenium is already running on port ////+ (r some other
serice is+
If this occurs you can either shutdo#n the other process that is using port 9999+ or you can tell Selenium,>rid to use a different port for its
hub- 5se the ,port option for changing the port used by the hub-
Kaa -Kar selenium-serer-standalone-#+#'+5+Kar -role hub -port ///'
This #ill #or' e.en if another hub is already running on the same machine+ that is+ as long as theyre both not using port 999F-
"ou may+ ho#e.er+ #ant to see #hat process is using port 9999 so you can allo# the hub to use the default- To see the ports used by all
running programs on your machine use the command-
netstat -a
This should #or' on all supported systems+ 5ni%GBinu%+ *ac6s+ and Windo#s although additional options beyond ,a may be re0uired-
Basically you need to display the process I( along #ith the port- In 5ni% you may ?grep the output ;use a pipe< from the port number to
only display those records youre concerned #ith-
Node Configuration
Timing arameters
.etting Command-6ine Help
The Selenium,Ser.er pro.ides listings of a.ailable options #ith a brief description of each- !urrently ;summer 78F7<+ the command,line
help has some oddities+ but it can be helpful if you 'no# #here to loo' and ho# to interpret the information-
The Selenium,Ser.er pro.ides t#o distinct functions+ that of the Selenium,2! ser.er and that of Selenium,>rid- These #ere li'ely #ritten
by different Selenium teams+ and therefore the command,line help for each function has ended up in t#o different places- And+ for the ne#
user+ it may not be apparent at first #hich of these t#o you are .ie#ing-
If you simply pass a ,h option as you might first assume+ you get the Selenium,2! Ser.er options but not those for Selenium,>rid-
Kaa -Kar selenium-serer-standalone-#+#'+5+Kar -h
This #ould gi.e you Selenium,2!s ser.er options- If you #ant the command,line help for Selenium,>rid+ you first use the ,hub or ,node
options to tell Selenium,Ser.er youre intereted in Selenium,>rid+ and then follo# #ith a ,h-
Kaa -Kar selenium-serer-standalone-#+#'+5+Kar -role node -h
6r+ for that matter+ just pass a garbage argument to the ,role node as follo#s-
Kaa -Kar selenium-serer-standalone-#+#'+5+Kar -role node ""
"ou #ill first see DIN$6---E and an D&2262E but belo# that youll get the command,line options for Selenium,>rid- We #ont list the
#hole output here since its rather long+ but the first fe# lines loo' li'e this-
Yul '4E #5'# '5?'5?.4 :N org+open=a+grid+selenium+Wrid,auncher main
PQ%(? ,aunching a selenium grid node
org+open=a+grid+common+e"ception+WridCon!iguration-"ception? Mou need to speci!y a hub to register to using
-hubLost V -hub&ort 0000+ The speci!ied con!ig was -hubLost null -hub&ort ////
at org+open=a+grid+common+IegistrationIe=uest+alidate(IegistrationIe=uest+Kaa?1'5)
at org+open=a+grid+internal+utils+$el!IegisteringIemote+startIemote$erer($el!IegisteringIemote+Kaa?33)
at org+open=a+grid+selenium+Wrid,auncher+main(Wrid,auncher+Kaa?2#)
-rror building the con!ig ?Mou need to speci!y a hub to register to using -hubLost V -hub&ort 0000+ The
speci!ied con!ig was -hubLost null -hub&ort ////
Jsage ?
-hubCon!ig?
(hub) a Y$(Q !ile !ollowing grid# !ormat+
-nodeTimeout?
(node) <VVVV> the timeout in seconds be!ore the hub
automatically ends a test that hasn9t had aby actiity than VV
sec+The browser will be released !or another test to use+This
typically ta<es care o! the client crashes+
Common ,rrors
@nable to acess the !arfile
Jnable to access Kar!ile selenium-serer-standalone-#+#'+5+Kar
This error can occur #hen starting up either a hub or node- This means :a.a cannot find the selenium,ser.er jar file- &ither run the command
from the directory #here the selenium,ser.er,OOOO-jar file is stored+ or specify an e%plicit path to the jar-
Troubleshooting
Table Of Contents
5ser,&%tensions
Introduction
Actions
AccessorsGAssertions
Bocator Strategies
5sing 5ser,&%tensions With Selenium,I(&
5sing 5ser,&%tensions With Selenium 2!
@ser-,3tensions
N-': his section is close to completion, but it has not been reviewed and edited.
Introduction
&%tending Selenium by adding your o#n actions+ assertions and locator,strategies can be 0uite simple- Add :a.aScript methods to the
Selenium object prototype and the PageBot object prototype- 6n startup+ Selenium #ill automatically loo' through methods on these
prototypes+ using name patterns to recogni/e #hich ones are actions+ assertions and locators- The follo#ing e%amples gi.e an indication of
ho# Selenium can be e%tended #ith :a.aScript-
Actions
All methods on the Selenium prototype beginning #ith DdoE are added as actions- $or each action foo there is also an action fooAndWait
registered- An action method can ta'e up to t#o parameters+ #hich #ill be passed the second and third column .alues in the test- &%ample1
Add a Dtype2epeatedE action to Selenium+ #hich types the te%t t#ice into a te%t bo%-
Accessors?Assertions
All get$oo and is$oo methods on the Selenium prototype are added as accessors ;store$oo<- $or each accessor there is an assert$oo+
.erify$oo and #ait$or$oo registered- An assert method can ta'e up to 7 parameters+ #hich #ill be passed the second and third column
.alues in the test- "ou can also define your o#n assertions literally as simple DassertE methods+ #hich #ill also auto,generate D.erifyE and
D#ait$orE commands- &%ample1 Add a .alue2epeated assertion+ that ma'es sure that the element .alue consists of the supplied te%t repeated-
The 7 commands that #ould be a.ailable in tests #ould be assert3alue2epeated and .erify3alue2epeated-
rototype generates additional commands
All get$oo and is$oo methods on the Selenium prototype automatically result in the a.ailability of store$oo+ assert$oo+ assertNot$oo+
.erify$oo+ .erifyNot$oo+ #ait$or$oo+ and #ait$orNot$oo commands- &%ample+ if you add a getTe"t,ength() method+ the follo#ing
commands #ill automatically be a.ailable1 storeTe"t,ength+ assertTe"t,ength+ assertQotTe"t,ength+
eri!yTe"t,ength+ eri!yQotTe"t,ength+ wait%orTe"t,ength+ and wait%orQotTe"t,ength commands-
Also note that the assertValueIepeated method described abo.e could ha.e been implemented using isValueIepeated+ #ith the
added benefit of also automatically getting assertNot3alue2epeated+ store3alue2epeated+ #ait$or3alue2epeated and
#ait$orNot3alue2epeated-
6ocator Strategies
All locate&lementBy$oo methods on the PageBot prototype are added as locator,strategies- A locator strategy ta'es 7 parameters+ the first
being the locator string ;minus the prefi%<+ and the second being the document in #hich to search- &%ample1 Add a D.aluerepeatedTE locator+
that finds the first element a .alue attribute e0ual to the the supplied .alue repeated-
@sing @ser-,3tensions With Selenium-I+,
5ser,e%tensions are .ery easy to use #ith the selenium I(&-
F- !reate your user e%tension and sa.e it as user,e%tensions-js- While this name isnt technically necessary+ its good practice to 'eep
things consistent-
7- 6pen $irefo% and open Selenium,I(&-
K- !lic' on Tools+ 6ptions
9- In Selenium !ore &%tensions clic' on Bro#se and find the user,e%tensions- js file- !lic' on 6A-
L- "our user,e%tension #ill not yet be loaded+ you must close and restart Selenium,I(&-
=- In your empty test+ create a ne# command+ your user,e%tension should no# be an options in the !ommands dropdo#n-
@sing @ser-,3tensions With Selenium *C
If you >oogle DSelenium 2! user,e%tensionE ten times you #ill find ten different approaches to using this feature- Belo#+ is the official
Selenium suggested approach-
,3ample
CU
F- Place your user e%tension in the same directory as your Selenium Ser.er-
7- If you are using client code generated by the Selenium,I(& you #ill need to ma'e a couple of small edits- $irst+ you #ill need to
create an LttpCommand&rocessor object #ith class scope ;outside the SetupTest method+ just belo# priate
$tringOuilder eri!ication-rrorsR<
LttpCommand&rocessor procR
K- Ne%t+ instantiate that LttpCommand&rocessor object as you #ould the De!ault$elenium object- This can be done in the
test setup-
proc ) new LttpCommand&rocessor(*localhost*E ////E *@ie"plore*E *http?//google+ca/*)R
9- Instantiate the (efaultSelenium object using the LttpCommand&rocessor object you created-
selenium ) new De!ault$elenium(proc)R
L- Within your test code+ e%ecute your user,e%tension by calling it #ith the DoCommand() method of LttpCommand&rocessor-
This method ta'es t#o arguments1 a string to identify the user,e%tension method you #ant to use and string array to pass arguments-
Notice that the first letter of your function is lo#er case+ regardless of the capitali/ation in your user,e%tension- Selenium
automatically does this to 'eep common :a.aScript naming con.entions- Because :a.aScript is case sensiti.e+ your test #ill fail if
you begin this command #ith a capital- inputParams is the array of arguments you #ant to pass to the :a.aScript user,e%tension- In
this case there is only one string in the array because there is only one parameter for our user e%tension+ but a longer array #ill map
each inde% to the corresponding user,e%tension parameter- 2emember that user e%tensions designed for Selenium,I(& #ill only ta'e
t#o arguments-
string67 input&arams ) D*Lello Torld*FR
proc+DoCommand(*alertTrapper*E input&arams)R
=- Start the test ser.er using the -user-"tensions argument and pass in your user-e"tensions+Ks file-
Kaa -Kar selenium-serer+Kar -user-"tensions user-e"tensions+Ks
Table Of Contents
Selenium Web(ri.er !heat Sheet
2ole Based Interfaces in Selenium Web(ri.er
Selenium Web+ri'er Cheat Sheet
*ole Based Interfaces in Selenium Web+ri'er
6ne of the differences bet#een Selenium 2! and Selenium Web(ri.er is that the Web(ri.er APIs ma'e e%tensi.e use of Drole,based
interfacesE to allo# users to determine #hether a particular dri.er supports a feature- This can ma'e it hard to 'no# #hat features are
a.ailable #ithout first 'no#ing #hich interface to try and use- The 'ey interfaces are listed belo#-
Interface *ole +ocumentation
Has!apabilities Pro.ides
access to the
capabilities
supported
by this
:a.a
Has!apabilities-ja.a
Interface *ole +ocumentation
dri.er-
:a.ascript&%ecutor Allo#s the
e%ecution of
arbitrary :S
commands-
:a.a
:a.ascript&%ecutor-ja.a
2otatable Indicates
#hether the
dri.er
supports
rotating the
display
;mostly just
mobile
dri.ers<-
:a.a 2otatable-ja.a
Ta'esScreenshot Pro.ides a
mechanism
for ta'ing
screenshots-
:a.a
Ta'esScreenshot-ja.a
org-open0a-selenium
Interface HasCapabilities
All Ano#n Implementing !lasses1
Android(ri.er+ !hrome(ri.er+ $irefo%(ri.er+ Html5nit(ri.er+ Internet&%plorer(ri.er+ IPhone(ri.er+ IPhoneSimulator(ri.er+
2emoteWeb(ri.er+ Safari(ri.er+ Web(ri.erBac'edSelenium
public inter!ace LasCapabilities
5sed by classes to indicate that they can describe the !apabilities they possess- This can be used for run,time detection of features-
7ethod Summary
*ethods
7odifier and Type 7ethod and +escription
!apabilities get!apabilities()
7ethod +etail
getCapabilities
Capabilities getCapabilities()
2eturns1
The capabilities of the current dri.er-
org-open0a-selenium
Interface Da'ascript,3ecutor
All Ano#n Implementing !lasses1
Android(ri.er+ AndroidWeb(ri.er+ !hrome(ri.er+ &.ent$iringWeb(ri.er+ $irefo%(ri.er+ Html5nit(ri.er+
Internet&%plorer(ri.er+ IPhone(ri.er+ IPhoneSimulator(ri.er+ 2emoteWeb(ri.er+ Safari(ri.er
public inter!ace Yaascript-"ecutor
Indicates that a dri.er can e%ecute :a.aScript+ pro.iding access to the mechanism to do so-
7ethod Summary
*ethods
7odifier and Type 7ethod and +escription
Kaa+lang+(bKect e%ecuteAsyncScript(Kaa+lang+$tring scriptE Kaa+lang+(bKect+++ args)
&%ecute an asynchronous piece of :a.aScript in the conte%t of the currently selected frame or
#indo#-
Kaa+lang+(bKect
e%ecuteScript(Kaa+lang+$tring scriptE Kaa+lang+(bKect+++ args)
&%ecutes :a.aScript in the conte%t of the currently selected frame or #indo#-
7ethod +etail
e3ecuteScript
Kaa+lang+(bKect e"ecute$cript(Kaa+lang+$tring scriptE
Kaa+lang+(bKect+++ args)
&%ecutes :a.aScript in the conte%t of the currently selected frame or #indo#- The script fragment pro.ided #ill be
e%ecuted as the body of an anonymous function-
Within the script+ use document to refer to the current document- Note that local .ariables #ill not be a.ailable once
the script has finished e%ecuting+ though global .ariables #ill persist-
If the script has a return .alue ;i-e- if the script contains a return statement<+ then the follo#ing steps #ill be ta'en1
$or an HT*B element+ this method returns a Web&lement
$or a decimal+ a (ouble is returned
$or a non,decimal number+ a Bong is returned
$or a boolean+ a Boolean is returned
$or all other cases+ a String is returned-
$or an array+ return a BistU6bjectQ #ith each object follo#ing the rules abo.e- We support nested lists-
5nless the .alue is null or there is no return .alue+ in #hich null is returned
Arguments must be a number+ a boolean+ a String+ Web&lement+ or a Bist of any combination of the abo.e- An
e%ception #ill be thro#n if the arguments do not meet these criteria- The arguments #ill be made a.ailable to the
:a.aScript .ia the eargumentse magic .ariable+ as if the function #ere called .ia e$unction-applye
Parameters1
script , The :a.aScript to e%ecute
args , The arguments to the script- *ay be empty
2eturns1
6ne of Boolean+ Bong+ String+ Bist or Web&lement- 6r null-
e3ecuteAsyncScript
Kaa+lang+(bKect e"ecute:sync$cript(Kaa+lang+$tring scriptE
Kaa+lang+(bKect+++ args)
&%ecute an asynchronous piece of :a.aScript in the conte%t of the currently selected frame or #indo#- 5nli'e
e%ecuting synchronous :a.aScript+ scripts e%ecuted #ith this method must e%plicitly signal they are finished by
in.o'ing the pro.ided callbac'- This callbac' is al#ays injected into the e%ecuted function as the last argument-
The first argument passed to the callbac' function #ill be used as the scriptVs result- This .alue #ill be handled as
follo#s1
$or an HT*B element+ this method returns a Web&lement
$or a number+ a Bong is returned
$or a boolean+ a Boolean is returned
$or all other cases+ a String is returned-
$or an array+ return a BistU6bjectQ #ith each object follo#ing the rules abo.e- We support nested lists-
5nless the .alue is null or there is no return .alue+ in #hich null is returned
&%ample HF1 Performing a sleep in the bro#ser under test-
long start ) $ystem+currentTimeNillis()R
((Yaascript-"ecutor) drier)+e"ecute:sync$cript(
*window+setTimeout(arguments6arguments+length - '7E 055)R*)R
$ystem+out+println(
*-lapsed time? * C $ystem+currentTimeNillis() - start)R

&%ample H71 Synchroni/ing a test #ith an A:AO application1
Teb-lement composeOutton ) drier+!ind-lement(Oy+id(*compose-button*))R
composeOutton+clic<()R
((Yaascript-"ecutor) drier)+e"ecute:sync$cript(
*ar callbac< ) arguments6arguments+length - '7R* C
*mailClient+getComposeTindowTidget()+onload(callbac<)R*)R
drier+switchTo()+!rame(*composeTidget*)R
drier+!ind-lement(Oy+id(*to*))+sendXeys(*bog8e"ample+com*)R

&%ample HK1 Injecting a O*BHttp2e0uest and #aiting for the result1
(bKect response ) ((Yaascript-"ecutor) drier)+e"ecute:sync$cript(
*ar callbac< ) arguments6arguments+length - '7R* C
*ar "hr ) new VN,LttpIe=uest()R* C
*"hr+open(9W-T9E 9/resource/data+Kson9E true)R* C
*"hr+onreadystatechange ) !unction() D* C
* i! ("hr+ready$tate )) /) D* C
* callbac<("hr+responseTe"t)R* C
* F* C
*FR* C
*"hr+send()R*)R
Y$(Q(bKect Kson ) new Y$(Q(bKect(($tring) response)R
assert-=uals(*cheese*E Kson+get$tring(*!ood*))R

Script arguments must be a number+ a boolean+ a String+ Web&lement+ or a Bist of any combination of the abo.e- An
e%ception #ill be thro#n if the arguments do not meet these criteria- The arguments #ill be made a.ailable to the
:a.aScript .ia the eargumentse .ariable-
Parameters1
script , The :a.aScript to e%ecute-
args , The arguments to the script- *ay be empty-
2eturns1
6ne of Boolean+ Bong+ String+ Bist+ Web&lement+ or null-
org-open0a-selenium
Interface *otatable
All Ano#n Implementing !lasses1
Android(ri.er+ AndroidWeb(ri.er
public inter!ace Iotatable
2epresents rotation of the bro#ser .ie# for orientation,sensiti.e de.ices- When using this #ith a real de.ice+ the de.ice should not be
mo.ed so that the built,in sensors do not interfere-
7ethod Summary
*ethods
7odifier and Type 7ethod and +escription
Screen6rientation get6rientation()
oid
rotate(Screen6rientation orientation)
!hanges the orientation of the bro#ser #indo#-
7ethod +etail
rotate
oid rotate($creen(rientation orientation)
!hanges the orientation of the bro#ser #indo#-
Parameters1
orientation , the desired screen orientation
getOrientation
$creen(rientation get(rientation()
2eturns1
the current screen orientation of the bro#ser
org-open0a-selenium
Interface Ta%esScreenshot
All Ano#n Implementing !lasses1
Android(ri.er+ AndroidWeb(ri.er+ !hrome(ri.er+ &.ent$iringWeb(ri.er+ $irefo%(ri.er+ Internet&%plorer(ri.er+
IPhone(ri.er+ IPhoneSimulator(ri.er+ Safari(ri.er
public inter!ace Ta<es$creenshot
Indicates a dri.er that can capture a screenshot and store it in different #ays-
&%ample usage1
import static open=a+selenium+(utputType+@R

%ile screenshot%ile ) (($creenshot)drier)+get$creenshot:s(!ile)R
$tring screenshotOase1/ ) (($creenshot)drier)+get$creenshot:s(base1/)R

See Also1
6utputType
7ethod Summary
*ethods
7odifier and Type 7ethod and +escription
<V> V
getScreenshotAs(6utputType<V> target)
!apture the screenshot and store it in the specified
location-
7ethod +etail
getScreenshotAs
<V> V get$creenshot:s((utputType<V> target)
throws TebDrier-"ception
!apture the screenshot and store it in the specified location-
$or Web(ri.er e%tending Ta'esScreenshot+ this ma'es a best effort depending on the bro#ser to return the follo#ing
in order of preference1
&ntire page
!urrent #indo#
3isible portion of the current frame
The screenshot of the entire display containing the bro#ser
$or Web&lement e%tending Ta'esScreenshot+ this ma'es a best effort depending on the bro#ser to return the follo#ing
in order of preference1 , The entire content of the HT*B element , The .isisble portion of the HT*B element
Type Parameters1
V , 2eturn type for getScreenshotAs-
Parameters1
target , target type+ ]see 6utputType
2eturns1
6bject in #hich is stored information about the screenshot-
Thro#s1
Web(ri.er&%ception , on failure-
&N,T client dri'er configuration
-N&T client (ri.er can be used #ith *icrosoft 3isual Studio- To !onfigure it #ith 3isual Studio do as $ollo#ing-
Baunch 3isual Studio and na.igate to $ile Q Ne# Q Project-

Select 3isual !H Q !lass Bibrary Q Name your project Q !lic' on 6A button-

A !lass ;-cs< is created- 2ename it as appropriate-
5nder right hand pane of Solution &%plorer right clic' on 2eferences Q Add 2eferences-

Select follo#ing dll files , nmoc'-dll+ nunit-core-dll+ nunit-frame#or'-dll+ThoughtWor's- Selenium-!ore-dll+
ThoughtWor's-Selenium-IntegrationTests-dll+ ThoughtWor's-Selenium-5nitTests-dll and clic' on 6' button

With This 3isual Studio is ready for Selenium Test !ases-
Table Of Contents
Importing Sel7-8 Project into &clipse using *a.en
Importing Sel7-8 Project into Intelli: 5sing *a.en
Importing Sel#&1 ro!ect into ,clipse using 7a'en
6nce you ha.e created your pom-%ml file in your project+ you can ha.e ma.en autogenerate the project files necessary for eclipse #ith a
simple command1
mn eclipse?eclipse
Then open eclipse- !hoose your #or'space or create a ne# one- 6nce the &clipse I(& loads+ do the follo#ing1
H $ile ,Q Import--- H >eneral ,Q &%isting Projects into Wor'space H !lic' ne%t H Ne%t to DSelect root (irectory1E clic' DBro#seE
button H locate the project folder containing your pom-%ml and clic' o'- H "our project should appear in the DProjectsE bo%
already H clic' finish
If you ha.ent already+ install the m7eclipse plugin then right clic' on your project and select *a.en ,Q &nable (ependency *anagement-
Importing Sel#&1 ro!ect into IntelliD @sing 7a'en
$e are currently working on this appendi%. he information provided here is accurate, although it may not be finished.
In this appendi% #e pro.ide the steps+ including screen captures+ sho#ing ho# to create a Selenium 7-8 ja.a client,dri.er project in Intelli:
I(&A- These steps assume you ha.e already used ma.en #ith a pom-%ml file to set up the project- This process is described in the Selenium
7-8 chapter- "ou must ha.e follo#ed that process before you can perform these steps- This appendi% then sho#s you ho# to import the
ma.en,created Selenium 7-8 ja.a project into Intelli:-
$irst+ open Intelli: and from the entry page+ clic' !reate Ne# Project-
$rom the Ne# Project dialog select Import Project from &%ternal *odel-

$rom the list of project types+ select ma.en-

No# you #ill see a dialog allo#ing you to set project options including the projects root directory-

!lic' the ?--- button to set the root folder-
No# the settings dialog #ill sho# the directory you just selected-
This ne%t dialog sho#s the name of your ma.en project as specified in the pom-%ml file- Select your ma.en project and continue-
&nter a name for your project-
6nce your project has been imported it should loo' li'e this in Intelli:-
The ma.en project do#nload many dependencies ;libraries< #hen you originally ran ?m.n install- No# in Intelli: you can see all these
libraries- These ne%t t#o screen captures sho#s the libraries you should no# ha.e in your project-
Before you can start #riting Selenium code+ you still need to create a module and at least one :a.a class ;a -ja.a file<- $irst select the
Projects root in Intelli: and right clic'-
And select !reate *odule-

In the dialog select the radio button !reate *odule $rom Scratch-
Select :a.a *odule and enter a name for the ne# module-
And ne%t+ you must create a folder for the source code- By con.ention this is almost al#ays named ?src-
No# #ere on the last dialog- Typically you dont need to select any ?technollogies here- 5nless you 'no# for a fact you #ill be using
>roo.y or some other technology-
No# that the module is created+ your project should sho# the follo#ing structure-

$inally+ you need to create a -ja.a file #ith a corresponding ja.a class-

&nter the class name-

The -ja.a file should no# be created- It should loo' li'e this in your project-
If your project no# loo's li'e the one displayed abo.e+ youre done+ congratsZ And hope you enjoy coding your first Selenium automationZ
Table Of Contents
Selenium F-8 :a.a !lient (ri.er !onfiguration
!onfiguring Selenium,2! With &clipse
!onfiguring Selenium,2! With Intellij
Selenium )&1 Da'a Client +ri'er Configuration
In >eneral configuration of Selenium,2! #ith any ja.a I(& #ould ha.e follo#ing steps1
(o#nload Selenium,2! from the SeleniumH4 do#nloads page
Start any ja.a I(&
!reate ne# project
Add Dselenium,ja.a,U.ersion,numberQ-jarE to your project classpath
2ecord your test from Selenium,I(& and translate it to ja.a code ;Selenium I(& has automatic translation feature to generate tests in
.ariety of languages<
2un selenium ser.er from console
2un your test in the I(&
These points ha.e been delineated belo# #ith reference to &clipse and Intelli:1
Configuring Selenium-*C With ,clipse
,clipse is a multi,language soft#are de.elopment platform comprising an I(& and a plug,in system to e%tend it- It is #ritten primarily in
:a.a and is used to de.elop applications in this language and+ by means of the .arious plug,ins+ in other languages as #ell as !G!JJ+ !obol+
Python+ Perl+ PHP and more-
$ollo#ing lines describes configuration of Selenium,2! #ith &clipse , 3ersion1 K-K-8- ;&uropa 2elease<- It should not be too different for
higher .ersions of &clipse
Baunch &clipse-
Select $ile Q Ne# Q 6ther-

:a.a Q :a.a Project Q Ne%t

Pro.ide Name to your project+ Select :(A in ?5se a project Specific :2& option ;:(A F-L selected in this e%ample< Q clic' Ne%t

Aeep ?:A3A Settings intact in ne%t #indo#- Project specific libraries can be added here- ;This described in detail in later part of
document-<

!lic' $inish Q !lic' on "es in 6pen Associated Perspecti.e pop up #indo#-

This #ould create Project >oogle in Pac'age &%plorerGNa.igator pane-

2ight clic' on src folder and clic' on Ne# Q $older

Name this folder as com and clic' on $inish button-
This should get com pac'age insider src folder-

$ollo#ing the same steps create core folder inside com

SelTest!ase class can be 'ept inside core pac'age-
!reate one more pac'age inside src folder named testscripts- This is a place holder for test scripts-
&lease notice this is about the organi!ation of proEect and it entirely depends on individual3s choice 6 organi!ation3s standards. est scripts
package can further be segregated depending upon the proEect reKuirements.

!reate a folder called lib inside project >oogle- 2ight clic' on Project name Q Ne# Q $older- This is a place holder for jar files to
project ;i-e- Selenium client dri.er+ selenium ser.er etc<

This #ould create lib folder in Project directory-

2ight clic' on lib folder Q Build Path Q !onfigure build Path

5nder Bibrary tab clic' on Add &%ternal :ars to na.igate to directory #here jar files are sa.ed- Select the jar files #hich are to be
added and clic' on 6pen button-

After ha.ing added jar files clic' on 6A button-

Added libraries #ould appear in Pac'age &%plorer as follo#ing1

Configuring Selenium-*C With Intelli!
Watch this e%cellent tutorial by Simon Ste#art on starting a Selenium project #ith Intelli:

You might also like