Tải bản đầy đủ (.pdf) (428 trang)

Selenium webdriver from foundations to framework

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (9.35 MB, 428 trang )


TableofContents
Introduction

1.1

Part1:Fundamentals

1.2

Chapter1:Firststeps

1.3

Chapter2:Locatingelementsonapage

1.4

Chapter3:Interactingwithelementsonapage

1.5

Chapter4:Examiningapage

1.6

Chapter4:MakingmaintainabletestsusingthePageObjectpattern

1.7

Chapter6:Whattodowhensomethinggoeswrong



1.8

Part2:WebDriverAPIsindepth

1.9

Chapter7:ManagingWebDriver

1.10

Chapter8:Windows,pop-ups,andframes

1.11

Chapter9:Unicornsandotherbeasts:exoticfeaturesofwebpages

1.12

Chapter10:ExecutingJavaScriptusingtheJavascriptExecutorinterface

1.13

Chapter11:Whatyouneedtoknowaboutdifferentbrowsers

1.14

Chapter12:WrappingWebDriverandWebElement

1.15


Part3:Pagebasedautomationframework

1.16

Chapter13:Formingaframework

1.17

Chapter14:Encapsulatingandgroupingelements

1.18

Chapter15:Automatingapageflow

1.19

Chapter16:ExaminingHTMLtables

1.20

Chapter17:AutomatingjQuerydatepicker

1.21

Chapter18:Datepickerframework

1.22

Appendices


1.23

AppendixA:Seleniumgrid

1.23.1

2


Introduction

Introduction
Thisbookisahands-onguidetodozensofspecificwaysyoucanusetogetthemostof
WebDriverinyourtestautomationdevelopment.Thispracticalhandbookgivesyou
instantly-usefulsolutionsforimportantareaslikeinteractingwithandtestingweb
applicationsandusingtheWebDriverAPIs.Asyouread,you’llgraduatefrom
WebDriverfundamentalstomust-havepracticesrangingfromhowtointeractwith,
controlandverifywebpagesandexceptionhandling,tomorecomplexinteractions
likepageobjects,alerts,andJavaScript,aswellas,mobiletesting,andmuchmore.
Finally,you’lllearnhowtobuildyourownframework.Bytheendofthebook,you’ll
beconfidentandskilledattestingyourwebapplicationswithWebDriver.

Aboutthetechnology
Webapplicationsaredifficulttotestbecausesomuchdependsonthewayauser
interactswithindividualpages.TheSeleniumWebDriverwebtestingframeworkhelps
youbuildreliableandmaintainabletestautomationforyourwebapplicationsacross
multiplebrowsers,operatingsystemsandprogramminglanguages.Muchlikeahuman,
itcanclickonlinks,filloutforms,andreadthewebpages,andunlikeahuman,it
doesnotgetbored.WebDrivercandonearlyanythingyouaskitto—thetrickisto

comeupwithaunifiedapproachtotesting.Fortunately,that’swherethisbookreally
shines.

What’sinside
Specific,practicalWebDrivertechniques
Interactingwith,controlling,andtestingwebapplications
UsingtheWebDriverAPIs
Makingmaintainabletests
Automatedtestingtechniques

Testimonials
3


Introduction
Quotesfromourearlyaccessreviewers:
Excellentcoverageofakeytechnologyinthewebtestingspace.
AnessentialbookforanyoneinterestedindoingWebDriverintegrationtesting.
YoushouldhavesomefamiliaritywithJavadevelopment(includingbasicuseof
Maven).ItstartswithbasicSeleniumWebDriverusagebutthere’splentymore.
It’sclearthattheauthorshavebeenusingthistechnologyinaprofessional
settingforquitesometimeasthebookislitteredwithonetechniqueafter
anotherwhichcanbeusedtoaddressproblemsonecanexpectwhentesting
realworldwebapplications.
ThisbookisaverypracticalguidetoSeleniumWebDriver.Thebookisloaded
withpracticalexampleswiththeirsolutions.Ihavealreadyusedtechniquesto
solveproblemsatwork.
It’sareallygoodintroductiontotheframeworkandIlikethewaytheauthors
haveattemptedtoprovidepracticalsolutionstotheproblemsonefaceswhen
tryingtoautomatecertaintypesoftests.


Acknowledgements
Thankyoutothefollowingcontributors:
entropicrune
Edko24
PulwerJR

ErrataandDiscussion
Ifyoufindanyerrorsorproblemswiththisbook,orifyouwanttotalkaboutthe
content:
/>
Aboutthereader

4


Introduction
Thisbookassumesyou’recomfortablereadingcodeinJavaorasimilarlanguageand
thatyouknowthebasicsofbuildingandtestingapplications.NoWebDriver
experienceisrequired.

Abouttheauthors

YujunLiangisaTechnicalAgileCoachwhoteachesagilesoftware
developmenttechnologiesincludingtestautomationusingSeleniumWebDriver.He
usedtoworkforThoughtWorksandhelpedclientsbuildautomationtestingforweb
applicationswithrichuserinteractionandcomplexbusinesslogic.

AlexCollinsisaTechnicalArchitectintheUK,atechnologyblogger,
publicspeaker,andOSScontributor.AlexhasbeenworkingwithSeleniumWebDriver

since2011.
Copyright©2016YujunLiangandAlexCollins

5


Part1:Fundamentals

Part1:Fundamentals
InthissectionwewillintroduceyoutoSeleniumWebDriver.We’llteachcommon
techniquesthatareusefulinwritingtests,suchaslocating,interactingandverifying
elements.We’llalsoshowyouhowtomakeyourcodemoremaintainableusingPage
Objectsandhowtodealwitherrors*You’llbeabletowritecodeformanycommon
webpagesbytheendofit.

6


Chapter1:Firststeps

Chapter1:FirstSteps
Thischaptercovers
WhatisWebDriver?
WhychooseWebDriver?
"HelloWebDriver!"
Nowadays,moreandmorebusinesstransactionsarecarriedoutontheInternet
throughwebpagesbuiltbypeople.Somewebsitesaresimpleenoughthattheycanbe
setupbyoneortwopeople,butsomewebsitesaresocomplexthattheyarebuiltby
hundredsoreventhousandsofdevelopers.Beforeeachrelease,thesitemustbe
testedtomakesureitisfreeofcriticalbugs.Itistime-consumingtotestthewhole

sitemanually,andasthesitegrows,sodoesthecostoftesting.Morethanthat,as
timepasses,anewfeaturethatwaswell-testedwhenitfirstbecameavailablemaybe
forgottenaboutlater—​weriskofalossofconsistencyandquality,andasaresultbugs
inwhatwethoughtweresolidpiecesoffunctionalitycreepin.
Inthetextileindustry,manuallabordominatedtheprocessofmakingclothesfora
longtime.Whenweavingmachineswereinvented,productivityimproved
dramatically.
Thesamethingishappeninginsoftwaretesting.Justasweavingmachineschanged
thetextileindustry,wearenowbuilding"automatictestingmachines"toreplace
manualtesting,toimprovetheproductivity,quality,andconsistencyofthesoftware.
Sinceitsinceptionin2008,SeleniumWebDriver(alsoknownasSelenium2)has
establisheditselfasthedefactowebautomationlibrary.
BeforeSeleniumWebDriver,therewasSelenium1.0,whichenabledautomationby
injectingJavaScriptintowebpages.WebDriverisare-inventionofthatidea,butis
morereliable,morepowerful,andmorescalable.
Seleniumhasevolved,andsohastheWorldWideWeb.HTML5andCSS3arenow
standard;AJAXrichwebapplicationsarenolongerevencuttingedge.Thismeansthat
webautomationisnowamorecomplexandinterestingtopic.
Thischapterwillrapidlycoverthebasics,makingsurethatbytheendofityou
understandthebasicarchitecturecanwritebasiccode.

7


Chapter1:Firststeps
Inthischapterwe’llintroduceWebDriver,whatitis,howitworks,andreasonsfor
choosingit.We’llalsobrieflytalkaboutsomeofthetoolsweusedinthisbook,the
oneswe’drecommendtoalldevelopers.

WhatisWebDriver?

SeleniumWebDriverautomateswebbrowsers.Itsitsintheplaceofthepersonusinga
webbrowser.Likeauser,itcanopenawebsite,clicklinks,fillinforms,andnavigate
around.Itcanalsoexaminethepage,lookingatelementsonitandmakingchoices
basedonwhatissees.
ThemostcommonusecaseforWebDriverisautomatedtesting.Untilrecently,torun
aregressiontestonyourwebsite,you’dneedtohaveasetofscriptsthatwouldhave
tobemanuallyexecutedbydevelopersorQAs.Anyreportswouldneedtobemanually
collatedtoo.Thiscanbebothtime-consumingandcostly.Instead,WebDrivercanbe
usedtoexecutethosescripts,andautomaticallygatherreportsonhowsuccessfulthey
were,atthepushofabutton.Eachsubsequentexecutionwillbenomoreexpensive
thanthefirst.

Figure1.BeforeWebDriver

8


Chapter1:Firststeps
Longgonearethedayswhenyouneededtocreateoneversiononyourwebsiteforthe
pervasiveandnotoriouslystandardsnon-compliantInternetExplorer6,andanotherfor
otherbrowsers.Whilemostmodernbrowsersaremuchmoreconsistentintheir
behavior,thewayawebpagelooksoractscanstillgreatlyvaryasthenumberof
differentbrowsers,operatingsystem,andplatformsincommonusehasincreased.You
canstillhaveahigh-valuecustomercomplainthattheycan’taccessyoursite.
Historically,theonlywaytomitigatethiswastohaveanarmyofQAsmanuallyteston
avarietyofdifferentconfigurations,atime-consumingandcostlyprocess.WebDriver
canruntestsondifferentoperatingsystemsanddifferentbrowserconfigurations,and
inafractionofthetimeofahumanbeing.Notonlythat,youcanuseittorunthem
muchmoreconsistentlyandreliablythanamanualtester.
Applicationsandwebsitesprovideusefulservices,butsometimestheseareonly

accessiblebywebpages.AnotherusecaseforWebDriveristomakethosepages
accessibletoapplicationsviaWebDriver.Youmighthaveanadministrationapplication
writtenseveralyearsagoandaclientorProductOwnerhasaskedforsomeactionson
ittobeautomated.Butmaybenooneknowswherethesourcecodeis.Itmightbe
mucheasiertouseWebDrivertoautomatethistask.

HowWebDriverworks
WebDriverworksinallmajorbrowsersandwithallmajorprogramminglanguages.
Howisthispossible?Well,WebDriverhasseveralinteractingcomponents:
1. Awebbrowser.
2. Apluginorextensiontothebrowserthatlivesinsidethebrowser,whichitself
containsaserverthatimplementstheWebDriverJSONAPI.
3. Alanguagebinding(inourcaseJava)thatmakesHTTPrequeststothatAPI.

9


Chapter1:Firststeps

Figure2.Webdriverdiagram
WhenyoustartcodethatusesWebDriver,itwillopenupthebrowser,whichinturn
startstheplugin.Youcanthensendrequeststoperformtheactionsyouwant,suchas
clickingonlinksortypingtext.AsapluginonlyneedstoimplementtheJSONAPI,
peoplehavewrittenpluginsforallmajorbrowsers.Touseabrowserthathasaplugin,
youjustneedtoimplementaclienttotheJSONprotocol.
Thismeansthatallthemajorbrowsersandallthemajorprogramminglanguages
supportWebDriver.
Theplugincanusuallybeseeninthebrowser’spreferences,suchasinfigure1.3.

10



Chapter1:Firststeps

Figure3.SafariExtensionspanel

WhychooseWebDriver?
ThereanumberofgreatreasonstochooseWebDriver:
WebDrivercanrunbrowserslocallyandremotelywithminimalconfiguration
changes.
WebDriverissupportedbymajorbrowservendors:bothFirefoxandChromeare
activeparticipantsinWebDriver’sdevelopment.
WebDrivermorecloselymimicsauser.Wherepossibleitusesnativeeventsto
operate,tomakeitaccurateandstable.
WebDriverisOpenSourceSoftware(OSS).Thismeansthatitisbothfreeandis
supportedbyanexcellentcommunity.
WebDriversupportsallmajoroperatingsystemssuchasOSX,Windows,and
Linux.ItalsohassupportforAndroidandiOS.
WebDriverisgoingtobecomeaW3Cstandard,soyoucanexpectthatitwillbe
supportedforalongtime.
WebDriverdoesn’tsufferfromsomeoftheproblemsthatSelenium1.0suffered
from,suchaswithuploadingfiles,orhandlingpop-ups.
WebDriverhasamoreconcisesyntaxthanSelenium1.0,makingitfastertowrite
code.

WhatWebDrivercannotdo
11


Chapter1:Firststeps

WebDriverprovidesawaytocontrolawebbrowser,butthatisall.Whenyoubuya
newcar,yougetamanualthatwilltellyouhowtooperatetheradioandhowto
changetheoil.Butthatmanualwon’ttellyouthebestplacetogetyourcarserviced,
orteachyouhowtodrive.Likedrivingacar,therearethingsyoumustdofor
yourself.HerearesomethingsWebDriverdoesnotdo:
WebDriverdoesn’thavethecontrolofthetimingoftheelementsappearingon
thewebpage.Somemightappearlaterandyou’llneedtohandlethisyourself.
WebDriverdoesnotknowwhenthingshavechangedonthepage,soyoucan’task
ittotellyouwhenthingshavechanged.
WebDriverdoesn’tprovidemanyutilitiesforwritingyourcode.Youneedtowrite
theseyourself.
WebDriverdoesn’tprovidebuilt-insupportforpageelementsthatarecomposed
ofmultipleelements,suchasJavaScriptcalendars.
WebDriverdoesnotprovideaframeworktowriteyourcodein.JUnitisanatural
choice.
WebDriverdoesn’tmanagethebrowser.Forexample,youneedtocleanupafter
youhaveusedit.
WebDriverwon’tinstallormaintainyourbrowsers.Youneedtodothisyourself.
We’llcoveralltheseimportanttasksinthisbook.

ThehistoryofSelenium
Seleniumisasuiteofwebtestingtools,includingSeleniumIDE,SeleniumRC,
SeleniumWebDriver,andSeleniumGrid.TheearliestSeleniumiscalledSelenium
Core,whichcameoutofThoughtWorks’sChicagoofficedevelopedbyJasonHuggins.
Itwaswrittentosimulateahumanuser’sactionwithInternetExplorer.Itwas
differentfromRecord/Replaytooltypesfromothervendors,sinceitdidn’trequirean
additionalGUItooltosupportitsoperation.ItjustneededJava,whichmost
developershadalreadyinstalledontheirmachines.
Later,ShinyaKasatanidevelopedaFirefoxplugincalledSeleniumIDEontopof
SeleniumCore.SeleniumIDEisagraphicinterfaceallowinguserstorecordabrowser

navigationsession,whichcanbereplayedafterwards.SeleniumIDEintegratedwith
FirefoxandprovidedthesameRecord/Replayfunctionastheotherproprietarytools.

12


Chapter1:Firststeps
SinceSeleniumIDEisafreetool,itsooncapturedabigmarketshareamongQAsand
businessanalystswhodidn’thavethenecessaryprogrammingskillstouseSelenium
Core.LaterSeleniumCoreevolvedintoSeleniumRC("RC"meaning"RemoteControl"),
alongwithSeleniumGrid,whichallowedtestscanberunonmanymachinesatthe
sametime.
SeleniumWebDriverwasoriginallycreatedbySimonStewartatThoughtworks.Itwas
originallypresentedatGoogleTestAutomationConference,andthiscanstillbeseen
online />In2008,SeleniumincorporatedWebDriverAPIandformedSelenium2.0.Selenium
WebDriverbecamethemostpopularchoiceamongtheSeleniumtoolsuite,sinceit
offersstandardizedoperationtovariousBrowsersthroughacommoninterface,
WebDriver.InfavorofthisnewsimplifiedWebDriverAPI,SeleniumRChasbeen
deprecatedanditsusageisnolongerencouraged.Thedeveloperswhomaintain
SeleniumalsoprovidedamigrationguidehelpingSeleniumRCusersmigratingfrom
SeleniumRCtoWebDriver.
Today,whenpeopletalkabout"Selenium,"they’reusuallytalkingaboutSelenium
WebDriver.
WhyitiscalledSelenium?
JasonHugginsjokedaboutacompetitornamedMercuryinanemail,sayingthatyou
cancuremercurypoisoningbytakingseleniumsupplements.That’swherethename
Seleniumcamefrom.

Thetoolsyouneedtogetstarted
Ontopofacomputer,accesstotheInternet,andadevelopmentenvironment,you

willneedsomeadditionalpiecesofsoftwaretogetstarted.
WhyweuseJavainthisbook
Whilewe’reawarethatmanydeveloperswon’tbeusingJavaastheirmainlanguage.
Wechoseitasthelanguageforthisbookbecausewewantedtowriteforthemost
peoplepossible,andJavaisthemostpopularprogramminglanguage.
TheAPItoWebDriverissimilarinalllanguages.Thelanguagesoftheweb — 
JavaScript,CSS,andHTML — arethesameregardlessofthelanguageyou’rewriting
yourtestsin.Ifyou’reusingoneofthemanylanguagesthatWebDriversupports,such

13


Chapter1:Firststeps
asC#,RubyorPython,youshouldbeabletoreplicatemanyofthetechniquesinthis
book.

JavaDevelopmentKit(JDK)
AsJavaisamongthemostpopularandwidelyuseddevelopmentlanguages,wewillbe
usingitthroughoutthisbook.Java8introducesanumberoffeatures,suchasstreams
andlambdaexpressions,thatmakeitfasterandmoreefficienttoworkwith
WebDriver.
Youcanchecktoseeif(andwhichversionof)theJDKisalreadyinstalledfroma
terminalusingthe javaccommand:
$javac-version
javac1.8.0_20

NotethatitistypicaltorefertoaJavaversionbythemiddledigitofthefullversion
number,so"Java1.8"isusuallyknownas"Java8."
LinuxuserscaninstallJavausingthe yumor aptpackagemanagers.Windowsand
OSXuserscandownloaditfromOracleat

/>
ApacheMaven
ThroughoutthisbookwewillusetheApacheMavenbuildtoolformanagingourcode.
ThemainreasonforthisisbecauseMavencanmanagethemanydependenciesthatwe
needtocreateanapplication.YoucanchecktoseeifyouhaveMaveninstalledfrom
theterminal:
$mvn-version
ApacheMaven3.3.1

Ifyoudonothaveitinstalled,Linuxuserscaninstallitusingtheirpackagemanager
(e.g.AptorYum),OSXuserscaninstallitusingtheHomebrewpackagemanage
()
Forexample(onOS-XusingBrew):
brewinstallmaven

14


Chapter1:Firststeps
Or(onUbuntuLinux):
sudoapt-getinstallmaven

WindowsuserscandownloaditfromtheApacheMavenwebsiteat
.

GoogleChrome
Çhromebrowseristhebestsupportedbrowser.Unlikeotherbrowsers,itisavailable
oneveryplatform,it’sstandardscompliant,andhasthesimpleout-of-the-box
integrationwithWebDriver.
Asusual,LinuxuserscaninstallChromeusingtheirpackagemanager;otherwiseyou

candownloadChromefromChrome.
LateronthebookwewilllookatotherbrowserssuchasFirefox,buthavingChrome
installednowwillgetyouthroughthefirstfewchapters.

Git
You’llneedtoinstallGitifyouwanttocheckoutthesourcecodeforthisbook.On
OS-XusingBrew:
brewinstallgit

OronUbuntuLinuxusingApt:
sudoapt-getinstallgit

IfyouuseWindows,youcandownloaditfrom.

Thetestproject
Aspartofthisproject,wehaveputallthesourcecodeintotheGitversioncontrol
system.Thiscontainsallthesamplecode,aswellasasmallwebsitethecoderuns
against.

15


Chapter1:Firststeps
Youcangetthisbyrunningthesecommands:
gitclone />cdsource

Theprojecthasabuilt-inwebserverthatcanbestartedbyenteringthefollowing:
mvnjetty:run

Youcanviewthewebsiteitcreatesathttp://localhost:8080/hello-webdriver.html.

YoushouldseeapagesimilartofigureHelloWebDriver.Thisformsthebasisofmany
ofthetestsintheproject,soyou’llprobablywanttokeepitrunningallthetime.

Figure4.HelloWebDriver
Whenyouaredone,press Ctrl+Ctoquittheserver.
Ifyouwanttofindexamplesfromthebookinthecode,lookforthepackagenamed
afterthechapter.Forexample,ifyou’relookingforchapterone’sexamples,then
theycanbefoundin src/test/java/swb/ch01intro.
Torunallthetestswiththebook,runthefollowing:
mvnverify

Instructionsonhowtorunwithdifferentbrowserscanbefoundinthe README.mdfile.

“HelloWebDriver!”
Let’slookatanexampleofusingWebDrivertoautomateabasictask,andendupwith
aworkingexample.AWebDriverautomationscriptusuallyconsistsofseveral
operations:
1. CreateanewWebDriver,backedbyeitheralocalorremotebrowser.

16


Chapter1:Firststeps
2. Openawebpage.
3. Interactwiththatpage,forexampleclickinglinksorenteringtext.
4. Checkwhetherthepagechangesasexpected.
5. InstructtheWebDrivertoquit.
Createadirectorywiththis pom.xml:
pom.xml
<?xmlversion="1.0"encoding="UTF-8"?>

xmlns=" />xsi:schemaLocation=" />





/>
<modelVersion>4.0.0</modelVersion>
<groupId>hello-webdriver</groupId>
<artifactId>hello-webdriver</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>(1)
<version>LATEST</version>(2)
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>


<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>

<configuration>
<source>1.8</source>(3)
<target>1.8</target>
</configuration>
</plugin>


17


Chapter1:Firststeps
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.18.1</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>(4)
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

1. Youcanchooseadifferentbrowser,e.g. selenium-firefox-driverisforthe
Firefoxbrowser.
2. Alwaysusethelatestversionthatisavailable.
3. CompileusingthelatestversionofJava — Java1.8.

4. MakesurethattestsarerunusingMaven’sfailsafeplugin.
Tostartthedriver,you’llneedaspecialbinaryprogramtostartitup.ForChrome,
thisiscalled chromedriverandcanbefoundat
Downloaditand
thensaveitintotherootoftheproject.
Create src/test/java/swb/intro/HelloWebDriverIT.java:
HelloWebDriverIT.java

18


Chapter1:Firststeps

packageswb.ch01intro;
importorg.junit.After;
importorg.junit.Before;
importorg.junit.Test;
importorg.openqa.selenium.By;(1)
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.chrome.ChromeDriver;
importstaticorg.junit.Assert.assertEquals;
publicclassHelloWebDriverIT{(2)
privateWebDriverdriver;
@Before
publicvoidsetUp()throwsException{
System.setProperty("webdriver.chrome.driver","chromedriver");(3)
driver=newChromeDriver();(4)
}
@After

publicvoidtearDown()throwsException{
driver.quit();(5)
}
@Test
publicvoidhelloWebDriver()throwsException{
driver.get("http://localhost:8080/hello-webdriver.html");(6)
WebElementpageHeading
=driver.findElement(By.tagName("h1"));(7)
assertEquals("HelloWebDriver!",
pageHeading.getText());(8)
}
}

1. StandardJavaimportsforWebDriver.
2. WeusetheITsuffixfortestinthisbook;thisistheMavenconventionfor
integrationteststhatrunusingtheFailsafeplugin[1].
3. Tellwebdriverviathissystempropertythelocationofthedriverbinary.
4. CreateanewdriverwhichconnectedtoaninstanceoftheChromebrowser.

19


Chapter1:Firststeps
5. Makesurethatthebrowserquitswhenthetestfinishes.
6. Openawebpageinthebrowser.
7. Locateanelementonthecurrentpage,inthiscasethepage’sheading.
8. Verifythattheheadingisthevalueyouexpect.
You’llneedtostartupthetestprojectasshownintheprevioussectionbeforeyourun
thetest.Then,whenyourunthetest,youshouldseethebrowseropenapagesimilar
tofigureHelloWebDriver.


Summary
YoucanuseWebDrivertosavetimeandmoneybyautomatingbrowsertasks.
Itisespeciallysuitedtoautomatedbrowsertesting.
WebDriverisbuiltaroundastandardJSONprotocol,andthatmeansallmajor
browsersandlanguagessupportit.
TherearesomegreatreasonstouseWebDriverovermanualtesting.Forexample,
youcansavecostsandimprovequalityatthesametime.
Youneedsometoolstogetstarted.We’llbeusingMavenandJavainthisbook.
Inthenextchapterwewillstartoutonourjourneybylookingatthefirstpartofany
automationscript—​locatingelementsonpages.

1. />
20


Chapter2:Locatingelementsonapage

Chapter2:Locatingelementsonapage
Thischaptercovers
LocatingelementsusingtheBylocators
Writingyourownlocatorfactories
Bestpracticesforchoosingandorganizinglocators
Asauser,thefirstthingyoudowhenopeningawebpageistrytofindthepartofthe
pageyou’reinterestedin.Ifitisoursocialnetwork,thismightbethenewmessages
icon;ifitisouronlinebanking,thismightbeourbalance.Youthenusethat
informationtoconsideryouractions.Inthesamemanner,WebDriverprovidesawide
varietyofmethodstolocateelementsonapage.Thisallowsustoexaminethepage
andenablesustocheckwhetherweseewhatweexpect.
Withouttheabilitytofindthoseelements,it’snotpossibletodoanyinteractionwith

thepage.Thismakesthetechniquesnecessarytodosoincrediblyimportant.
Inthischapterwe’llcoverallthemainmethodsforlocatingelementsonpages.We
willalsolookathowtocomposethosebasicbuildingblockstogetherintomore
complicatedlocators.Locatingelementsisonlyhalfthestory.Wewillalsocoverways
tomanagethedifferentlocatingstrategiesyoumightwanttousetomakeyourcode
friendlyandeasytoworkwith.
Unlikehumanperception,WebDriver’smethodsareverystrict.Ifyou’relookingfor
thenewmessagesicon,youmightbelookingforsomethingthatlookslikean
envelope,butifthatenvelopeisonedaybiggerorsmaller,oradifferentcolorthan
howyouremember,youwilladapt.WebDriverdoesn’thavethatintelligence.Ifthe
iconchangesfromanenvelopetosomethingelse,mostuserswouldquicklypickupon
thechange,butnoteveryWebDriverinvocationwould.Wewilllookatpatternsyou
canusetomakesurethatyourcoderemainsrobusttochangesinthepagethatmight
otherwisebreakyourcodeandcreateamaintenanceissue.
Notonlywillweintroduceyoutoallthemainelementlocationmethods,we’llcover
whateachoneismoresuitedfor,aswellasorganizationpractices.Finally,wewill
lookathowtomakethesiteyouareautomatingeasytoautomate.

21


Chapter2:Locatingelementsonapage
Astheendofthechapteryouwillhaveanexcellenttoolboxofrobuststrategiesfor
locatingelementsofalltypes.

LocatingoneormoreelementsbasedonID,
class,orname
WebDriverprovidesanumberofwaystolocateelements.We’lllookathowthis
works,andthemainwaysyoucanachievethis.


Whatisasearchcontext?
LocatingelementsonanypageoccurswithinwhatWebDriverreferstoasasearch
context.Let’squicklylookatthe SearchContextinterface:
publicinterfaceSearchContext{
List<WebElement>findElements(Byby);
WebElementfindElement(Byby);
}

Thisinterfaceprovidestwomethods:onethatfindsalltheelementsthatmatchan
instanceofwhatisknownasalocator,andasecondthatfindsthefirstelementthat
matches,orthrowsa NoSuchElementExceptionifitisnotfound.Thatmeansthe
findElementsmethodisusefulforfindingelementswhenyou’renotsureiftheywill

beonthepage,orifyouwanttomakesurethey’renotonthepage.
Boththe WebElementand WebDriverinterfacesextend SearchContext,soalldrivers
andelementswillhavethesemethods.

Whatisalocator?
Alocatordescribeswhatyouwanttofind,andthereisazooofthem.InJava,you
createalocatorusingthe Byclass.Let’slookatanexampleoffindingan h1
headingelementonthecurrentpage:
WebElementheading1Element=driver.findElement(By.tagName("h1"));

And,forcompleteness,findingalltheparagraphelementsinthecurrentpage:

22


Chapter2:Locatingelementsonapage


List<WebElement>paragraphElement=driver.findElements(By.tagName("p"));

Asdiscussed,thereareanumberofcorelocatorsyoucanusetofindelementsona
page.
Locator

Usage

ClassName

Locateselementsbythevalueofthe
"class"attribute.

CSSSelector

Locateselementsviathedriver’s
underlyingW3CSSSelectorengine.If
thebrowserdoesnotimplementthe
SelectorAPI,abesteffortismadeto
emulatetheAPI.Inthiscase,it
strivesforatleastCSS2support,but
itoffernoguarantees.

ID

Locateselementsbythevalueoftheir
idattribute.

LinkText


Locateselementsbytheexacttextit
displays

Name

Locateselementsbythevalueoftheir
nameattribute.

PartialLinkText

Locateselementsthatcontainthe
givenlinktext

TagName

Locateselementsbytheirtagname

XPath

LocateselementsviaXPath

Locatingbylinktext
Linktextisthepreferredlocatorforlinks.FigureLoginform
http://localhost:8080/login.htmlshowsthelinkonthetestapp’sloginpagefor
forgottenpasswords:

23


Chapter2:Locatingelementsonapage


Figure1.Loginformhttp://localhost:8080/login.html
ThisisrepresentedbythefollowingHTML:
<ahref="#"id="change-password"class="btn">ForgottenPassword</a>

Andthiscanbelocatedusingthefollowing:
driver.findElement(By.linkText("ForgottenPassword"));

Anypartofthestring“ForgottenPassword”canbeusedastheparameterforthis
method:
driver.findElement(By.partialLinkText("ForgottenPassword"));
driver.findElement(By.partialLinkText("Forgotten"));
driver.findElement(By.partialLinkText("enPasswo"));

Youshouldbecautiouswhenusing findElementwiththislocator.Youmayfindother
elementsthatcontainthesamepartialtext,sothisshouldnotbeusedtolocatea
singleelementonitsown.Naturally,youcanuseittolocateagroupofelements
usingthe findElementsmethod.

Locatingbyclassattribute
Thislocateselementsbythevalueofthe classattribute.Thiscanbeusedonlyfor
thoseelementshavinga classattribute,butitisnotagoodselectortousewiththe
findElementmethod.Classisusedforstylingpages,andasaresultmanyelements

arelikelytohavethesameclass.As findElementalwaysreturnsthefirstelementit
finds,iftheelementyouwantisnotinthefirstplace,youwon’tbeabletousethisto
locateit.Evenifitisthefirstelementnow,ifadeveloperaddsanewelementwith
thesameclassearlierinthepage,itwillreturnthenewlyaddedelement,insteadof
theelementyou’retryingtolocate.Thismakesforbrittlecode.
IntheloginpageinfigureLoginformhttp://localhost:8080/login.html,the“Forgotten

Password”linkhasoneCSSclass: btn;youcanuseclassname btntolocateit:

24


Chapter2:Locatingelementsonapage

driver.findElement(By.className("btn"))

LocatingbyID
Locatinganelementbyits idattributecanbeexpressedasthefollowing:
driver.findElement(By.id("change-password"))

IfthesiteisbuiltusingJavaScript,IDisnormallyappliedtoimportantelements.IDs
aremeanttobeunique,soifanelementhasanID,it’susuallythemostaccurateway
toidentifytheelement.WhileIDscanaccidentallyappearmultipletimesonapage
(forexample,duetoaprogrammingerror),thisisrare.Sincetheyareoftenaddedto
facilitateJavaScriptcode,ifthismistakeoccurs,theJavaScriptwillusuallybefaulty
too,andthereforethiswillbespottedearlyindevelopment.
IfIDisavailable,makeityourfirstchoice.

Locatingbyinputname
Thisisalocatorwhichlocateselementsbythevalueofthe nameattribute.Normally
itcanonlybeusedtolocateformelementsbuiltusing: <input>, <button>,
<select>,and <textarea>.Remember,ifthesamenameisusedformultiple

elementsonthesamepage,onlythefirstencounteredelementwillbereturned.So
beforeusingthislocator,youneedtocheckwhetherthenameisuniqueonthepage.
Ifitis,thenitcanbeused;otherwise,otherlocators(orcombinationthereof)will
needtobeused.

Ontheloginpage,thereisanemailinput:
<inputname="email"class="form-control"placeholder="Email"/>

Sothecodeyouwouldneedwouldbethefollowing:
driver.findElement(By.name("email"));

Locatingbyelementtagname

25


×