Sie sind auf Seite 1von 47

14/8/2015

SeleniumReference

SeleniumReference
1. Concepts
1. ElementLocators
2. ElementFilters
3. StringmatchPatterns
2. SeleniumActions
3. SeleniumAccessors
4. ParameterConstructionandVariables
5. WhitespaceRules
6. ExtendingSelenium

Concepts
AcommandiswhattellsSeleniumwhattodo.Seleniumcommandscomeinthree'flavors':Actions,
AccessorsandAssertions.Eachcommandcallisonelineinthetesttableoftheform:
command target

value

Actionsarecommandsthatgenerallymanipulatethestateoftheapplication.Theydothingslike"click
thislink"and"selectthatoption".IfanActionfails,orhasanerror,theexecutionofthecurrenttestis
stopped.
ManyActionscanbecalledwiththe"AndWait"suffix,e.g."clickAndWait".ThissuffixtellsSelenium
thattheactionwillcausethebrowsertomakeacalltotheserver,andthatSeleniumshouldwaitfora
newpagetoload.
Accessorsexaminethestateoftheapplicationandstoretheresultsinvariables,e.g."storeTitle".They
arealsousedtoautomaticallygenerateAssertions.
AssertionsarelikeAccessors,buttheyverifythatthestateoftheapplicationconformstowhatis
expected.Examplesinclude"makesurethepagetitleisX"and"verifythatthischeckboxischecked".
AllSeleniumAssertionscanbeusedin3modes:"assert","verify",and"waitFor".Forexample,youcan
"assertText","verifyText"and"waitForText".Whenan"assert"fails,thetestisaborted.Whena"verify"
fails,thetestwillcontinueexecution,loggingthefailure.Thisallowsasingle"assert"toensurethatthe
applicationisonthecorrectpage,followedbyabunchof"verify"assertionstotestformfieldvalues,
labels,etc.
"waitFor"commandswaitforsomeconditiontobecometrue(whichcanbeusefulfortestingAjax
applications).Theywillsucceedimmediatelyiftheconditionisalreadytrue.However,theywillfailand
haltthetestiftheconditiondoesnotbecometruewithinthecurrenttimeoutsetting(seethesetTimeout
actionbelow).
ElementLocatorstellSeleniumwhichHTMLelementacommandrefersto.Manycommandsrequire
anElementLocatorasthe"target"attribute.ExamplesofElementLocatorsinclude"elementId"and
"document.forms[0].element".Thesearedescribedmoreclearlyinthenextsection.
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

1/47

14/8/2015

SeleniumReference

Patternsareusedforvariousreasons,e.g.tospecifytheexpectedvalueofaninputfield,oridentifya
selectoption.Seleniumsupportsvarioustypesofpattern,includingregularexpressions,allofwhichare
describedinmoredetailbelow.
DefinesanobjectthatrunsSeleniumcommands.

ElementLocators
ElementLocatorstellSeleniumwhichHTMLelementacommandrefersto.Theformatofalocatoris:
locatorType=argument
Wesupportthefollowingstrategiesforlocatingelements:
identifier=id:Selecttheelementwiththespecified@idattribute.Ifnomatchisfound,selectthe
firstelementwhose@nameattributeisid.(Thisisnormallythedefaultseebelow.)
id=id:Selecttheelementwiththespecified@idattribute.
name=name:Selectthefirstelementwiththespecified@nameattribute.
username
name=username
Thenamemayoptionallybefollowedbyoneormoreelementfilters,separatedfromthenameby
whitespace.IfthefilterTypeisnotspecified,valueisassumed.
name=flavourvalue=chocolate
dom=javascriptExpression:Findanelementbyevaluatingthespecifiedstring.Thisallowsyouto
traversetheHTMLDocumentObjectModelusingJavaScript.Notethatyoumustnotreturna
valueinthisstringsimplymakeitthelastexpressionintheblock.
dom=document.forms['myForm'].myDropdown
dom=document.images[56]
dom=functionfoo(){returndocument.links[1]}foo()
xpath=xpathExpression:LocateanelementusinganXPathexpression.
xpath=//img[@alt='Theimagealttext']
xpath=//table[@id='table1']//tr[4]/td[2]
xpath=//a[contains(@href,'#id1')]
xpath=//a[contains(@href,'#id1')]/@class
xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td
xpath=//input[@name='name2'and@value='yes']
xpath=//*[text()="right"]
link=textPattern:Selectthelink(anchor)elementwhichcontainstextmatchingthespecified
pattern.
link=Thelinktext
css=cssSelectorSyntax:Selecttheelementusingcssselectors.PleaserefertoCSS2selectors,CSS3
selectorsformoreinformation.YoucanalsochecktheTestCssLocatorstestintheseleniumtest
suiteforanexampleofusage,whichisincludedinthedownloadedseleniumcorepackage.
css=a[href="#id3"]
css=span#firstChild+span
Currentlythecssselectorlocatorsupportsallcss1,css2andcss3selectorsexceptnamespacein
css3,somepseudoclasses(:nthoftype,:nthlastoftype,:firstoftype,:lastoftype,:onlyoftype,
:visited,:hover,:active,:focus,:indeterminate)andpseudoelements(::firstline,::firstletter,
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

2/47

14/8/2015

SeleniumReference

::selection,::before,::after).
ui=uiSpecifierString:LocateanelementbyresolvingtheUIspecifierstringtoanotherlocator,and
evaluatingit.SeetheSeleniumUIElementReferenceformoredetails.
ui=loginPages::loginButton()
ui=settingsPages::toggle(label=HideEmail)
ui=forumPages::postBody(index=2)//a[2]
Withoutanexplicitlocatorprefix,Seleniumusesthefollowingdefaultstrategies:
dom,forlocatorsstartingwith"document."
xpath,forlocatorsstartingwith"//"
identifier,otherwise

ElementFilters
Elementfilterscanbeusedwithalocatortorefinealistofcandidateelements.Theyare
currentlyusedonlyinthe'name'elementlocator.
Filterslookmuchlikelocators,ie.
filterType=argument
Supportedelementfiltersare:
value=valuePattern
Matcheselementsbasedontheirvalues.Thisisparticularlyusefulforrefininga
listofsimilarlynamedtogglebuttons.
index=index
Selectsasingleelementbasedonitspositioninthelist(offsetfromzero).

StringmatchPatterns
VariousPatternsyntaxesareavailableformatchingstringvalues:
glob:pattern:Matchastringagainsta"glob"(aka"wildmat")pattern."Glob"isakindoflimited
regularexpressionsyntaxtypicallyusedincommandlineshells.Inaglobpattern,"*"represents
anysequenceofcharacters,and"?"representsanysinglecharacter.Globpatternsmatchagainst
theentirestring.
regexp:regexp:Matchastringusingaregularexpression.ThefullpowerofJavaScriptregular
expressionsisavailable.
regexpi:regexpi:Matchastringusingacaseinsensitiveregularexpression.
exact:string:Matchastringexactly,verbatim,withoutanyofthatfancywildcardstuff.
Ifnopatternprefixisspecified,Seleniumassumesthatit'sa"glob"pattern.
Forcommandsthatreturnmultiplevalues(suchasverifySelectOptions),thestringbeingmatchedisa
commaseparatedlistofthereturnvalues,wherebothcommasandbackslashesinthevaluesare
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

3/47

14/8/2015

SeleniumReference

backslashescaped.Whenprovidingapattern,theoptionalmatchingsyntax(i.e.glob,regexp,etc.)is
specifiedonce,asusual,atthebeginningofthepattern.

SeleniumActions
addLocationStrategy(strategyName,functionDefinition)
DefinesanewfunctionforSeleniumtolocateelementsonthepage.Forexample,ifyoudefinethe
strategy"foo",andsomeonerunsclick("foo=blah"),we'llrunyourfunction,passingyouthestring
"blah",andclickontheelementthatyourfunctionreturns,orthrowan"Elementnotfound"error
ifyourfunctionreturnsnull.We'llpassthreeargumentstoyourfunction:
locator:thestringtheuserpassedin
inWindow:thecurrentlyselectedwindow
inDocument:thecurrentlyselecteddocument
Thefunctionmustreturnnulliftheelementcan'tbefound.
Arguments:
strategyNamethenameofthestrategytodefinethisshoulduseonlyletters[azAZ]with
nospacesorotherpunctuation.
functionDefinitionastringdefiningthebodyofafunctioninJavaScript.Forexample:
returninDocument.getElementById(locator);

addScript(scriptContent,scriptTagId)
LoadsscriptcontentintoanewscripttagintheSeleniumdocument.Thisdiffersfromthe
runScriptcommandinthatrunScriptaddsthescripttagtothedocumentoftheAUT,notthe
Seleniumdocument.Thefollowingentitiesinthescriptcontentarereplacedbythecharactersthey
represent:<>&ThecorrespondingremovecommandisremoveScript.
Arguments:
scriptContenttheJavascriptcontentofthescripttoadd
scriptTagId(optional)theidofthenewscripttag.Ifspecified,andanelementwiththisid
alreadyexists,thisoperationwillfail.
addSelection(locator,optionLocator)
Addaselectiontothesetofselectedoptionsinamultiselectelementusinganoptionlocator.
@see#doSelectfordetailsofoptionlocators
Arguments:
locatoranelementlocatoridentifyingamultiselectbox
optionLocatoranoptionlocator(alabelbydefault)
allowNativeXpath(allow)
SpecifieswhetherSeleniumshouldusethenativeinbrowserimplementationofXPath(ifany
nativeversionisavailable)ifyoupass"false"tothisfunction,wewillalwaysuseourpure
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

4/47

14/8/2015

SeleniumReference

JavaScriptxpathlibrary.UsingthepureJSxpathlibrarycanimprovetheconsistencyofxpath
elementlocatorsbetweendifferentbrowservendors,butthepureJSversionismuchslowerthan
thenativeimplementations.
Arguments:
allowboolean,truemeanswe'llprefertousenativeXPathfalsemeanswe'llonlyuseJS
XPath
altKeyDown()
PressthealtkeyandholditdownuntildoAltUp()iscalledoranewpageisloaded.
altKeyUp()
Releasethealtkey.
answerOnNextPrompt(answer)
InstructsSeleniumtoreturnthespecifiedanswerstringinresponsetothenextJavaScriptprompt
[window.prompt()].
Arguments:
answertheanswertogiveinresponsetothepromptpopup
assignId(locator,identifier)
Temporarilysetsthe"id"attributeofthespecifiedelement,soyoucanlocateitinthefutureusing
itsIDratherthanaslow/complicatedXPath.ThisIDwilldisappearoncethepageisreloaded.
Arguments:
locatoranelementlocatorpointingtoanelement
identifierastringtobeusedastheIDofthespecifiedelement
break()
Haltthecurrentlyrunningtest,andwaitfortheusertopresstheContinuebutton.Thiscommandis
usefulfordebugging,butbecarefulwhenusingit,becauseitwillforceautomatedteststohang
untilauserintervenesmanually.
captureEntirePageScreenshot(filename,kwargs)
SavestheentirecontentsofthecurrentwindowcanvastoaPNGfile.Contrastthiswiththe
captureScreenshotcommand,whichcapturesthecontentsoftheOSviewport(i.e.whateveris
currentlybeingdisplayedonthemonitor),andisimplementedintheRConly.Currentlythisonly
worksinFirefoxwhenrunninginchromemode,andinIEnonHTAusingtheEXPERIMENTAL
"Snapsie"utility.TheFirefoximplementationismostlyborrowedfromtheScreengrab!Firefox
extension.Pleaseseehttp://www.screengrab.organdhttp://snapsie.sourceforge.net/fordetails.
Arguments:
filenamethepathtothefiletopersistthescreenshotas.Nofilenameextensionwillbe
appendedbydefault.Directorieswillnotbecreatediftheydonotexist,andanexception
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

5/47

14/8/2015

SeleniumReference

willbethrown,possiblybynativecode.
kwargsakwargsstringthatmodifiesthewaythescreenshotiscaptured.Example:
"background=#CCFFDD".Currentlyvalidoptions:
background
thebackgroundCSSfortheHTMLdocument.Thismaybeusefultosetforcapturing
screenshotsoflessthanideallayouts,forexamplewhereabsolutepositioningcauses
thecalculationofthecanvasdimensiontofailandablackbackgroundisexposed
(possiblyobscuringblacktext).
check(locator)
Checkatogglebutton(checkbox/radio)
Arguments:
locatoranelementlocator
chooseCancelOnNextConfirmation()
Bydefault,Selenium'soverriddenwindow.confirm()functionwillreturntrue,asiftheuserhad
manuallyclickedOKafterrunningthiscommand,thenextcalltoconfirm()willreturnfalse,asif
theuserhadclickedCancel.Seleniumwillthenresumeusingthedefaultbehaviorforfuture
confirmations,automaticallyreturningtrue(OK)unless/untilyouexplicitlycallthiscommandfor
eachconfirmation.
Takenoteeverytimeaconfirmationcomesup,youmustconsumeitwithacorresponding
getConfirmation,orelsethenextseleniumoperationwillfail.
chooseOkOnNextConfirmation()
UndotheeffectofcallingchooseCancelOnNextConfirmation.NotethatSelenium'soverridden
window.confirm()functionwillnormallyautomaticallyreturntrue,asiftheuserhadmanually
clickedOK,soyoushouldn'tneedtousethiscommandunlessforsomereasonyouneedtochange
yourmindpriortothenextconfirmation.Afteranyconfirmation,Seleniumwillresumeusingthe
defaultbehaviorforfutureconfirmations,automaticallyreturningtrue(OK)unless/untilyou
explicitlycallchooseCancelOnNextConfirmationforeachconfirmation.
Takenoteeverytimeaconfirmationcomesup,youmustconsumeitwithacorresponding
getConfirmation,orelsethenextseleniumoperationwillfail.
click(locator)
Clicksonalink,button,checkboxorradiobutton.Iftheclickactioncausesanewpagetoload
(likealinkusuallydoes),callwaitForPageToLoad.
Arguments:
locatoranelementlocator
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

6/47

14/8/2015

SeleniumReference

clickAt(locator,coordString)
Clicksonalink,button,checkboxorradiobutton.Iftheclickactioncausesanewpagetoload
(likealinkusuallydoes),callwaitForPageToLoad.
Arguments:
locatoranelementlocator
coordStringspecifiesthex,yposition(i.e.10,20)ofthemouseeventrelativetothe
elementreturnedbythelocator.
close()
Simulatestheuserclickingthe"close"buttoninthetitlebarofapopupwindowortab.
contextMenu(locator)
Simulatesopeningthecontextmenuforthespecifiedelement(asmighthappeniftheuser"right
clicked"ontheelement).
Arguments:
locatoranelementlocator
contextMenuAt(locator,coordString)
Simulatesopeningthecontextmenuforthespecifiedelement(asmighthappeniftheuser"right
clicked"ontheelement).
Arguments:
locatoranelementlocator
coordStringspecifiesthex,yposition(i.e.10,20)ofthemouseeventrelativetothe
elementreturnedbythelocator.
controlKeyDown()
PressthecontrolkeyandholditdownuntildoControlUp()iscalledoranewpageisloaded.
controlKeyUp()
Releasethecontrolkey.
createCookie(nameValuePair,optionsString)
Createanewcookiewhosepathanddomainaresamewiththoseofcurrentpageundertest,unless
youspecifiedapathforthiscookieexplicitly.
Arguments:
nameValuePairnameandvalueofthecookieinaformat"name=value"
optionsStringoptionsforthecookie.Currentlysupportedoptionsinclude'path','max_age'
and'domain'.theoptionsString'sformatis"path=/path/,max_age=60,domain=.foo.com".
Theorderofoptionsareirrelevant,theunitofthevalueof'max_age'issecond.Notethat
specifyingadomainthatisn'tasubsetofthecurrentdomainwillusuallyfail.
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

7/47

14/8/2015

SeleniumReference

deleteAllVisibleCookies()
CallsdeleteCookiewithrecurse=trueonallcookiesvisibletothecurrentpage.Asnotedonthe
documentationfordeleteCookie,recurse=truecanbemuchslowerthansimplydeletingthecookies
usingaknowndomain/path.
deleteCookie(name,optionsString)
Deleteanamedcookiewithspecifiedpathanddomain.Becarefultodeleteacookie,youneedto
deleteitusingtheexactsamepathanddomainthatwereusedtocreatethecookie.Ifthepathis
wrong,orthedomainiswrong,thecookiesimplywon'tbedeleted.Alsonotethatspecifyinga
domainthatisn'tasubsetofthecurrentdomainwillusuallyfail.Sincethere'snowaytodiscover
atruntimetheoriginalpathanddomainofagivencookie,we'veaddedanoptioncalled'recurse'to
tryallsubdomainsofthecurrentdomainwithallpathsthatareasubsetofthecurrentpath.
Bewarethisoptioncanbeslow.InbigOnotation,itoperatesinO(n*m)time,wherenisthe
numberofdotsinthedomainnameandmisthenumberofslashesinthepath.
Arguments:
namethenameofthecookietobedeleted
optionsStringoptionsforthecookie.Currentlysupportedoptionsinclude'path','domain'
and'recurse.'TheoptionsString'sformatis"path=/path/,domain=.foo.com,recurse=true".
Theorderofoptionsareirrelevant.Notethatspecifyingadomainthatisn'tasubsetofthe
currentdomainwillusuallyfail.
deselectPopUp()
Selectsthemainwindow.FunctionallyequivalenttousingselectWindow()andspecifyingnovalue
forwindowID.
doubleClick(locator)
Doubleclicksonalink,button,checkboxorradiobutton.Ifthedoubleclickactioncausesanew
pagetoload(likealinkusuallydoes),callwaitForPageToLoad.
Arguments:
locatoranelementlocator
doubleClickAt(locator,coordString)
Doubleclicksonalink,button,checkboxorradiobutton.Iftheactioncausesanewpagetoload
(likealinkusuallydoes),callwaitForPageToLoad.
Arguments:
locatoranelementlocator
coordStringspecifiesthex,yposition(i.e.10,20)ofthemouseeventrelativetothe
elementreturnedbythelocator.
dragAndDrop(locator,movementsString)
Dragsanelementacertaindistanceandthendropsit
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

8/47

14/8/2015

SeleniumReference

Arguments:
locatoranelementlocator
movementsStringoffsetinpixelsfromthecurrentlocationtowhichtheelementshouldbe
moved,e.g.,"+70,300"
dragAndDropToObject(locatorOfObjectToBeDragged,locatorOfDragDestinationObject)
Dragsanelementanddropsitonanotherelement
Arguments:
locatorOfObjectToBeDraggedanelementtobedragged
locatorOfDragDestinationObjectanelementwhoselocation(i.e.,whosecentermostpixel)
willbethepointwherelocatorOfObjectToBeDraggedisdropped
dragdrop(locator,movementsString)
deprecatedusedragAndDropinstead
Arguments:
locatoranelementlocator
movementsStringoffsetinpixelsfromthecurrentlocationtowhichtheelementshouldbe
moved,e.g.,"+70,300"
echo(message)
PrintsthespecifiedmessageintothethirdtablecellinyourSelenesetables.Usefulfordebugging.
Arguments:
messagethemessagetoprint
fireEvent(locator,eventName)
Explicitlysimulateanevent,totriggerthecorresponding"onevent"handler.
Arguments:
locatoranelementlocator
eventNametheeventname,e.g."focus"or"blur"
focus(locator)
Movethefocustothespecifiedelementforexample,iftheelementisaninputfield,movethe
cursortothatfield.
Arguments:
locatoranelementlocator
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

9/47

14/8/2015

SeleniumReference

goBack()
Simulatestheuserclickingthe"back"buttonontheirbrowser.
highlight(locator)
BrieflychangesthebackgroundColorofthespecifiedelementyellow.Usefulfordebugging.
Arguments:
locatoranelementlocator
ignoreAttributesWithoutValue(ignore)
SpecifieswhetherSeleniumwillignorexpathattributesthathavenovalue,i.e.aretheempty
string,whenusingthenonnativexpathevaluationengine.You'dwanttodothisforperformance
reasonsinIE.However,thiscouldbreakcertainxpaths,forexampleanxpaththatlooksforan
attributewhosevalueisNOTtheemptystring.Thehopeisthatsuchxpathsarerelativelyrare,but
theusershouldhavetheoptionofusingthem.Notethatthisonlyinfluencesxpathevaluationwhen
usingtheajaxsltengine(i.e.not"javascriptxpath").
Arguments:
ignoreboolean,truemeanswe'llignoreattributeswithoutvalueattheexpenseofxpath
"correctness"falsemeanswe'llsacrificespeedforcorrectness.
keyDown(locator,keySequence)
Simulatesauserpressingakey(withoutreleasingityet).
Arguments:
locatoranelementlocator
keySequenceEitherbeastring("\"followedbythenumerickeycodeofthekeytobe
pressed,normallytheASCIIvalueofthatkey),orasinglecharacter.Forexample:"w",
"\119".
keyPress(locator,keySequence)
Simulatesauserpressingandreleasingakey.
Arguments:
locatoranelementlocator
keySequenceEitherbeastring("\"followedbythenumerickeycodeofthekeytobe
pressed,normallytheASCIIvalueofthatkey),orasinglecharacter.Forexample:"w",
"\119".
keyUp(locator,keySequence)
Simulatesauserreleasingakey.
Arguments:
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

10/47

14/8/2015

SeleniumReference

locatoranelementlocator
keySequenceEitherbeastring("\"followedbythenumerickeycodeofthekeytobe
pressed,normallytheASCIIvalueofthatkey),orasinglecharacter.Forexample:"w",
"\119".
metaKeyDown()
PressthemetakeyandholditdownuntildoMetaUp()iscalledoranewpageisloaded.
metaKeyUp()
Releasethemetakey.
mouseDown(locator)
Simulatesauserpressingtheleftmousebutton(withoutreleasingityet)onthespecifiedelement.
Arguments:
locatoranelementlocator
mouseDownAt(locator,coordString)
Simulatesauserpressingtheleftmousebutton(withoutreleasingityet)atthespecifiedlocation.
Arguments:
locatoranelementlocator
coordStringspecifiesthex,yposition(i.e.10,20)ofthemouseeventrelativetothe
elementreturnedbythelocator.
mouseDownRight(locator)
Simulatesauserpressingtherightmousebutton(withoutreleasingityet)onthespecifiedelement.
Arguments:
locatoranelementlocator
mouseDownRightAt(locator,coordString)
Simulatesauserpressingtherightmousebutton(withoutreleasingityet)atthespecifiedlocation.
Arguments:
locatoranelementlocator
coordStringspecifiesthex,yposition(i.e.10,20)ofthemouseeventrelativetothe
elementreturnedbythelocator.
mouseMove(locator)
Simulatesauserpressingthemousebutton(withoutreleasingityet)onthespecifiedelement.
Arguments:
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

11/47

14/8/2015

SeleniumReference

locatoranelementlocator
mouseMoveAt(locator,coordString)
Simulatesauserpressingthemousebutton(withoutreleasingityet)onthespecifiedelement.
Arguments:
locatoranelementlocator
coordStringspecifiesthex,yposition(i.e.10,20)ofthemouseeventrelativetothe
elementreturnedbythelocator.
mouseOut(locator)
Simulatesausermovingthemousepointerawayfromthespecifiedelement.
Arguments:
locatoranelementlocator
mouseOver(locator)
Simulatesauserhoveringamouseoverthespecifiedelement.
Arguments:
locatoranelementlocator
mouseUp(locator)
Simulatestheeventthatoccurswhentheuserreleasesthemousebutton(i.e.,stopsholdingthe
buttondown)onthespecifiedelement.
Arguments:
locatoranelementlocator
mouseUpAt(locator,coordString)
Simulatestheeventthatoccurswhentheuserreleasesthemousebutton(i.e.,stopsholdingthe
buttondown)atthespecifiedlocation.
Arguments:
locatoranelementlocator
coordStringspecifiesthex,yposition(i.e.10,20)ofthemouseeventrelativetothe
elementreturnedbythelocator.
mouseUpRight(locator)
Simulatestheeventthatoccurswhentheuserreleasestherightmousebutton(i.e.,stopsholding
thebuttondown)onthespecifiedelement.
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

12/47

14/8/2015

SeleniumReference

Arguments:
locatoranelementlocator
mouseUpRightAt(locator,coordString)
Simulatestheeventthatoccurswhentheuserreleasestherightmousebutton(i.e.,stopsholding
thebuttondown)atthespecifiedlocation.
Arguments:
locatoranelementlocator
coordStringspecifiesthex,yposition(i.e.10,20)ofthemouseeventrelativetothe
elementreturnedbythelocator.
open(url)
OpensanURLinthetestframe.ThisacceptsbothrelativeandabsoluteURLs.The"open"
commandwaitsforthepagetoloadbeforeproceeding,ie.the"AndWait"suffixisimplicit.Note:
TheURLmustbeonthesamedomainastherunnerHTMLduetosecurityrestrictionsinthe
browser(SameOriginPolicy).IfyouneedtoopenanURLonanotherdomain,usetheSelenium
Servertostartanewbrowsersessiononthatdomain.
Arguments:
urltheURLtoopenmayberelativeorabsolute
openWindow(url,windowID)
Opensapopupwindow(ifawindowwiththatIDisn'talreadyopen).Afteropeningthewindow,
you'llneedtoselectitusingtheselectWindowcommand.
ThiscommandcanalsobeausefulworkaroundforbugSEL339.Insomecases,Seleniumwillbe
unabletointerceptacalltowindow.open(ifthecalloccursduringorbeforethe"onLoad"event,
forexample).Inthosecases,youcanforceSeleniumtonoticetheopenwindow'snamebyusing
theSeleniumopenWindowcommand,usinganempty(blank)url,likethis:openWindow("",
"myFunnyWindow").
Arguments:
urltheURLtoopen,whichcanbeblank
windowIDtheJavaScriptwindowIDofthewindowtoselect
pause(waitTime)
Waitforthespecifiedamountoftime(inmilliseconds)
Arguments:
waitTimetheamountoftimetosleep(inmilliseconds)

http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

13/47

14/8/2015

SeleniumReference

refresh()
Simulatestheuserclickingthe"Refresh"buttonontheirbrowser.
removeAllSelections(locator)
Unselectsalloftheselectedoptionsinamultiselectelement.
Arguments:
locatoranelementlocatoridentifyingamultiselectbox
removeScript(scriptTagId)
RemovesascripttagfromtheSeleniumdocumentidentifiedbythegivenid.Doesnothingifthe
referencedtagdoesn'texist.
Arguments:
scriptTagIdtheidofthescriptelementtoremove.
removeSelection(locator,optionLocator)
Removeaselectionfromthesetofselectedoptionsinamultiselectelementusinganoption
locator.@see#doSelectfordetailsofoptionlocators
Arguments:
locatoranelementlocatoridentifyingamultiselectbox
optionLocatoranoptionlocator(alabelbydefault)
rollup(rollupName,kwargs)
Executesacommandrollup,whichisaseriesofcommandswithauniquename,andoptionally
argumentsthatcontrolthegenerationofthesetofcommands.Ifanyoneoftherolledup
commandsfails,therollupisconsideredtohavefailed.Rollupsmayalsocontainnestedrollups.
Arguments:
rollupNamethenameoftherollupcommand
kwargskeywordargumentsstringthatinfluenceshowtherollupexpandsintocommands
runScript(script)
Createsanew"script"taginthebodyofthecurrenttestwindow,andaddsthespecifiedtextinto
thebodyofthecommand.Scriptsruninthiswaycanoftenbedebuggedmoreeasilythanscripts
executedusingSelenium's"getEval"command.BewarethatJSexceptionsthrowninthesescript
tagsaren'tmanagedbySelenium,soyoushouldprobablywrapyourscriptintry/catchblocksif
thereisanychancethatthescriptwillthrowanexception.
Arguments:
scripttheJavaScriptsnippettorun
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

14/47

14/8/2015

SeleniumReference

select(selectLocator,optionLocator)
Selectanoptionfromadropdownusinganoptionlocator.
OptionlocatorsprovidedifferentwaysofspecifyingoptionsofanHTMLSelectelement(e.g.for
selectingaspecificoption,orforassertingthattheselectedoptionsatisfiesaspecification).There
areseveralformsofSelectOptionLocator.
label=labelPattern:matchesoptionsbasedontheirlabels,i.e.thevisibletext.(Thisisthe
default.)
label=regexp:^[Oo]ther
value=valuePattern:matchesoptionsbasedontheirvalues.
value=other
id=id:matchesoptionsbasedontheirids.
id=option1
index=index:matchesanoptionbasedonitsindex(offsetfromzero).
index=2
Ifnooptionlocatorprefixisprovided,thedefaultbehaviouristomatchonlabel.
Arguments:
selectLocatoranelementlocatoridentifyingadropdownmenu
optionLocatoranoptionlocator(alabelbydefault)
selectFrame(locator)
Selectsaframewithinthecurrentwindow.(Youmayinvokethiscommandmultipletimesto
selectnestedframes.)Toselecttheparentframe,use"relative=parent"asalocatortoselectthe
topframe,use"relative=top".Youcanalsoselectaframebyits0basedindexnumberselectthe
firstframewith"index=0",orthethirdframewith"index=2".
YoumayalsouseaDOMexpressiontoidentifytheframeyouwantdirectly,likethis:
dom=frames["main"].frames["subframe"]

Arguments:
locatoranelementlocatoridentifyingaframeoriframe
selectPopUp(windowID)
Simplifiestheprocessofselectingapopupwindow(anddoesnotofferfunctionalitybeyondwhat
selectWindow()alreadyprovides).
IfwindowIDiseithernotspecified,orspecifiedas"null",thefirstnontopwindowisselected.
ThetopwindowistheonethatwouldbeselectedbyselectWindow()withoutprovidinga
windowID.Thisshouldnotbeusedwhenmorethanonepopupwindowisinplay.
Otherwise,thewindowwillbelookedupconsideringwindowIDasthefollowinginorder:1)
the"name"ofthewindow,asspecifiedtowindow.open()2)ajavascriptvariablewhichisa
referencetoawindowand3)thetitleofthewindow.Thisisthesameorderedlookup
performedbyselectWindow.
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

15/47

14/8/2015

SeleniumReference

Arguments:
windowIDanidentifierforthepopupwindow,whichcantakeonanumberofdifferent
meanings
selectWindow(windowID)
Selectsapopupwindowusingawindowlocatoronceapopupwindowhasbeenselected,all
commandsgotothatwindow.Toselectthemainwindowagain,usenullasthetarget.
Windowlocatorsprovidedifferentwaysofspecifyingthewindowobject:bytitle,byinternal
JavaScript"name,"orbyJavaScriptvariable.
title=MySpecialWindow:Findsthewindowusingthetextthatappearsinthetitlebar.Be
carefultwowindowscansharethesametitle.Ifthathappens,thislocatorwilljustpickone.
name=myWindow:FindsthewindowusingitsinternalJavaScript"name"property.Thisis
thesecondparameter"windowName"passedtotheJavaScriptmethodwindow.open(url,
windowName,windowFeatures,replaceFlag)(whichSeleniumintercepts).
var=variableName:Somepopupwindowsareunnamed(anonymous),butareassociated
withaJavaScriptvariablenameinthecurrentapplicationwindow,e.g."window.foo=
window.open(url)".Inthosecases,youcanopenthewindowusing"var=foo".
Ifnowindowlocatorprefixisprovided,we'lltrytoguesswhatyoumeanlikethis:
1.)ifwindowIDisnull,(orthestring"null")thenitisassumedtheuserisreferringtotheoriginal
windowinstantiatedbythebrowser).
2.)ifthevalueofthe"windowID"parameterisaJavaScriptvariablenameinthecurrent
applicationwindow,thenitisassumedthatthisvariablecontainsthereturnvaluefromacalltothe
JavaScriptwindow.open()method.
3.)Otherwise,seleniumlooksinahashitmaintainsthatmapsstringnamestowindow"names".
4.)Ifthatfails,we'lltryloopingoveralloftheknownwindowstotrytofindtheappropriate
"title".Since"title"isnotnecessarilyunique,thismayhaveunexpectedbehavior.
Ifyou'rehavingtroublefiguringoutthenameofawindowthatyouwanttomanipulate,lookatthe
Seleniumlogmessageswhichidentifythenamesofwindowscreatedviawindow.open(and
thereforeinterceptedbySelenium).Youwillseemessageslikethefollowingforeachwindowasit
isopened:
debug:window.opencallintercepted;windowID(whichyoucanusewithselectWindow())is
"myNewWindow"

Insomecases,Seleniumwillbeunabletointerceptacalltowindow.open(ifthecalloccursduring
orbeforethe"onLoad"event,forexample).(ThisisbugSEL339.)Inthosecases,youcanforce
Seleniumtonoticetheopenwindow'snamebyusingtheSeleniumopenWindowcommand,using
anempty(blank)url,likethis:openWindow("","myFunnyWindow").
Arguments:
windowIDtheJavaScriptwindowIDofthewindowtoselect
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

16/47

14/8/2015

SeleniumReference

setBrowserLogLevel(logLevel)
Setsthethresholdforbrowsersideloggingmessageslogmessagesbeneaththisthresholdwillbe
discarded.ValidlogLevelstringsare:"debug","info","warn","error"or"off".Toseethebrowser
logs,youneedtoeithershowthelogwindowinGUImode,orenablebrowsersideloggingin
SeleniumRC.
Arguments:
logLeveloneofthefollowing:"debug","info","warn","error"or"off"
setCursorPosition(locator,position)
Movesthetextcursortothespecifiedpositioninthegiveninputelementortextarea.Thismethod
willfailifthespecifiedelementisn'taninputelementortextarea.
Arguments:
locatoranelementlocatorpointingtoaninputelementortextarea
positionthenumericalpositionofthecursorinthefieldpositionshouldbe0tomovethe
positiontothebeginningofthefield.Youcanalsosetthecursorto1tomoveittotheend
ofthefield.
setMouseSpeed(pixels)
Configurethenumberofpixelsbetween"mousemove"eventsduringdragAndDropcommands
(default=10).
Settingthisvalueto0meansthatwe'llsenda"mousemove"eventtoeverysinglepixelinbetween
thestartlocationandtheendlocationthatcanbeveryslow,andmaycausesomebrowsersto
forcetheJavaScripttotimeout.
Ifthemousespeedisgreaterthanthedistancebetweenthetwodraggedobjects,we'lljustsendone
"mousemove"atthestartlocationandthenonefinaloneattheendlocation.
Arguments:
pixelsthenumberofpixelsbetween"mousemove"events
setSpeed(value)
Setexecutionspeed(i.e.,setthemillisecondlengthofadelaywhichwillfolloweachselenium
operation).Bydefault,thereisnosuchdelay,i.e.,thedelayis0milliseconds.
Arguments:
valuethenumberofmillisecondstopauseafteroperation
setTimeout(timeout)
SpecifiestheamountoftimethatSeleniumwillwaitforactionstocomplete.
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

17/47

14/8/2015

SeleniumReference

Actionsthatrequirewaitinginclude"open"andthe"waitFor*"actions.
Thedefaulttimeoutis30seconds.
Arguments:
timeoutatimeoutinmilliseconds,afterwhichtheactionwillreturnwithanerror
shiftKeyDown()
PresstheshiftkeyandholditdownuntildoShiftUp()iscalledoranewpageisloaded.
shiftKeyUp()
Releasetheshiftkey.
store(expression,variableName)
ThiscommandisasynonymforstoreExpression.
Arguments:
expressionthevaluetostore
variableNamethenameofavariableinwhichtheresultistobestored.
submit(formLocator)
Submitthespecifiedform.Thisisparticularlyusefulforformswithoutsubmitbuttons,e.g.single
input"Search"forms.
Arguments:
formLocatoranelementlocatorfortheformyouwanttosubmit
type(locator,value)
Setsthevalueofaninputfield,asthoughyoutypeditin.
Canalsobeusedtosetthevalueofcomboboxes,checkboxes,etc.Inthesecases,valueshouldbe
thevalueoftheoptionselected,notthevisibletext.
Arguments:
locatoranelementlocator
valuethevaluetotype
typeKeys(locator,value)
Simulateskeystrokeeventsonthespecifiedelement,asthoughyoutypedthevaluekeybykey.
ThisisaconveniencemethodforcallingkeyDown,keyUp,keyPressforeverycharacterinthe
specifiedstringthisisusefulfordynamicUIwidgets(likeautocompletingcomboboxes)that
requireexplicitkeyevents.
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

18/47

14/8/2015

SeleniumReference

Unlikethesimple"type"command,whichforcesthespecifiedvalueintothepagedirectly,this
commandmayormaynothaveanyvisibleeffect,evenincaseswheretypingkeyswouldnormally
haveavisibleeffect.Forexample,ifyouuse"typeKeys"onaformelement,youmayormaynot
seetheresultsofwhatyoutypedinthefield.
Insomecases,youmayneedtousethesimple"type"commandtosetthevalueofthefieldand
thenthe"typeKeys"commandtosendthekeystrokeeventscorrespondingtowhatyoujusttyped.
Arguments:
locatoranelementlocator
valuethevaluetotype
uncheck(locator)
Uncheckatogglebutton(checkbox/radio)
Arguments:
locatoranelementlocator
useXpathLibrary(libraryName)
Allowschoiceofoneoftheavailablelibraries.
Arguments:
libraryNamenameofthedesiredlibraryOnlythefollowingthreecanbechosen:
"ajaxslt"Google'slibrary
"javascriptxpath"CybozuLabs'fasterlibrary
"default"Thedefaultlibrary.Currentlythedefaultlibraryis"ajaxslt".
IflibraryNameisn'toneofthesethree,thennochangewillbemade.
waitForCondition(script,timeout)
RunsthespecifiedJavaScriptsnippetrepeatedlyuntilitevaluatesto"true".Thesnippetmayhave
multiplelines,butonlytheresultofthelastlinewillbeconsidered.
Notethat,bydefault,thesnippetwillberunintherunner'stestwindow,notinthewindowofyour
application.Togetthewindowofyourapplication,youcanusetheJavaScriptsnippet
selenium.browserbot.getCurrentWindow(),andthenrunyourJavaScriptinthere
Arguments:
scripttheJavaScriptsnippettorun
timeoutatimeoutinmilliseconds,afterwhichthiscommandwillreturnwithanerror
waitForFrameToLoad(frameAddress,timeout)
Waitsforanewframetoload.
Seleniumconstantlykeepstrackofnewpagesandframesloading,andsetsa"newPageLoaded"
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

19/47

14/8/2015

SeleniumReference

flagwhenitfirstnoticesapageload.
SeewaitForPageToLoadformoreinformation.
Arguments:
frameAddressFrameAddressfromtheserverside
timeoutatimeoutinmilliseconds,afterwhichthiscommandwillreturnwithanerror
waitForPageToLoad(timeout)
Waitsforanewpagetoload.
Youcanusethiscommandinsteadofthe"AndWait"suffixes,"clickAndWait","selectAndWait",
"typeAndWait"etc.(whichareonlyavailableintheJSAPI).
Seleniumconstantlykeepstrackofnewpagesloading,andsetsa"newPageLoaded"flagwhenit
firstnoticesapageload.RunninganyotherSeleniumcommandafterturnstheflagtofalse.Hence,
ifyouwanttowaitforapagetoload,youmustwaitimmediatelyafteraSeleniumcommandthat
causedapageload.
Arguments:
timeoutatimeoutinmilliseconds,afterwhichthiscommandwillreturnwithanerror
waitForPopUp(windowID,timeout)
Waitsforapopupwindowtoappearandloadup.
Arguments:
windowIDtheJavaScriptwindow"name"ofthewindowthatwillappear(notthetextof
thetitlebar)Ifunspecified,orspecifiedas"null",thiscommandwillwaitforthefirstnon
topwindowtoappear(don'trelyonthisifyouareworkingwithmultiplepopups
simultaneously).
timeoutatimeoutinmilliseconds,afterwhichtheactionwillreturnwithanerror.Ifthis
valueisnotspecified,thedefaultSeleniumtimeoutwillbeused.SeethesetTimeout()
command.
windowFocus()
Givesfocustothecurrentlyselectedwindow
windowMaximize()
Resizecurrentlyselectedwindowtotakeuptheentirescreen

SeleniumAccessors
assertErrorOnNext(message)
TellSeleniumtoexpectanerroronthenextcommandexecution.
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

20/47

14/8/2015

SeleniumReference

Arguments:
messageTheerrormessageweshouldexpect.Thiscommandwillfailifthewrongerror
messageappears.
RelatedAssertions,automaticallygenerated:
assertNotErrorOnNext(message)
verifyErrorOnNext(message)
verifyNotErrorOnNext(message)
waitForErrorOnNext(message)
waitForNotErrorOnNext(message)
assertFailureOnNext(message)
TellSeleniumtoexpectafailureonthenextcommandexecution.
Arguments:
messageThefailuremessageweshouldexpect.Thiscommandwillfailifthewrong
failuremessageappears.
RelatedAssertions,automaticallygenerated:
assertNotFailureOnNext(message)
verifyFailureOnNext(message)
verifyNotFailureOnNext(message)
waitForFailureOnNext(message)
waitForNotFailureOnNext(message)
assertSelected(selectLocator,optionLocator)
VerifiesthattheselectedoptionofadropdownsatisfiestheoptionSpecifier.Notethatthis
commandisdeprecatedyoushoulduseassertSelectedLabel,assertSelectedValue,
assertSelectedIndex,orassertSelectedIdinstead.
Seetheselectcommandformoreinformationaboutoptionlocators.
Arguments:
selectLocatoranelementlocatoridentifyingadropdownmenu
optionLocatoranoptionlocator,typicallyjustanoptionlabel(e.g."JohnSmith")
RelatedAssertions,automaticallygenerated:
assertNotSelected(selectLocator,optionLocator)
verifySelected(selectLocator,optionLocator)
verifyNotSelected(selectLocator,optionLocator)
waitForSelected(selectLocator,optionLocator)
waitForNotSelected(selectLocator,optionLocator)

http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

21/47

14/8/2015

SeleniumReference

storeAlert(variableName)
RetrievesthemessageofaJavaScriptalertgeneratedduringthepreviousaction,orfailifthere
werenoalerts.
GettinganalerthasthesameeffectasmanuallyclickingOK.Ifanalertisgeneratedbutyoudo
notconsumeitwithgetAlert,thenextSeleniumactionwillfail.
UnderSelenium,JavaScriptalertswillNOTpopupavisiblealertdialog.
SeleniumdoesNOTsupportJavaScriptalertsthataregeneratedinapage'sonload()eventhandler.
InthiscaseavisibledialogWILLbegeneratedandSeleniumwillhanguntilsomeonemanually
clicksOK.
Returns:
ThemessageofthemostrecentJavaScriptalert
RelatedAssertions,automaticallygenerated:
assertAlert(pattern)
assertNotAlert(pattern)
verifyAlert(pattern)
verifyNotAlert(pattern)
waitForAlert(pattern)
waitForNotAlert(pattern)
storeAllButtons(variableName)
ReturnstheIDsofallbuttonsonthepage.
IfagivenbuttonhasnoID,itwillappearas""inthisarray.
Returns:
theIDsofallbuttonsonthepage
RelatedAssertions,automaticallygenerated:
assertAllButtons(pattern)
assertNotAllButtons(pattern)
verifyAllButtons(pattern)
verifyNotAllButtons(pattern)
waitForAllButtons(pattern)
waitForNotAllButtons(pattern)
storeAllFields(variableName)
ReturnstheIDsofallinputfieldsonthepage.
IfagivenfieldhasnoID,itwillappearas""inthisarray.
Returns:
theIDsofallfieldonthepage
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

22/47

14/8/2015

SeleniumReference

RelatedAssertions,automaticallygenerated:
assertAllFields(pattern)
assertNotAllFields(pattern)
verifyAllFields(pattern)
verifyNotAllFields(pattern)
waitForAllFields(pattern)
waitForNotAllFields(pattern)
storeAllLinks(variableName)
ReturnstheIDsofalllinksonthepage.
IfagivenlinkhasnoID,itwillappearas""inthisarray.
Returns:
theIDsofalllinksonthepage
RelatedAssertions,automaticallygenerated:
assertAllLinks(pattern)
assertNotAllLinks(pattern)
verifyAllLinks(pattern)
verifyNotAllLinks(pattern)
waitForAllLinks(pattern)
waitForNotAllLinks(pattern)
storeAllWindowIds(variableName)
ReturnstheIDsofallwindowsthatthebrowserknowsaboutinanarray.
Returns:
Arrayofidentifiersofallwindowsthatthebrowserknowsabout.
RelatedAssertions,automaticallygenerated:
assertAllWindowIds(pattern)
assertNotAllWindowIds(pattern)
verifyAllWindowIds(pattern)
verifyNotAllWindowIds(pattern)
waitForAllWindowIds(pattern)
waitForNotAllWindowIds(pattern)
storeAllWindowNames(variableName)
Returnsthenamesofallwindowsthatthebrowserknowsaboutinanarray.
Returns:
Arrayofnamesofallwindowsthatthebrowserknowsabout.
RelatedAssertions,automaticallygenerated:
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

23/47

14/8/2015

SeleniumReference

assertAllWindowNames(pattern)
assertNotAllWindowNames(pattern)
verifyAllWindowNames(pattern)
verifyNotAllWindowNames(pattern)
waitForAllWindowNames(pattern)
waitForNotAllWindowNames(pattern)
storeAllWindowTitles(variableName)
Returnsthetitlesofallwindowsthatthebrowserknowsaboutinanarray.
Returns:
Arrayoftitlesofallwindowsthatthebrowserknowsabout.
RelatedAssertions,automaticallygenerated:
assertAllWindowTitles(pattern)
assertNotAllWindowTitles(pattern)
verifyAllWindowTitles(pattern)
verifyNotAllWindowTitles(pattern)
waitForAllWindowTitles(pattern)
waitForNotAllWindowTitles(pattern)
storeAttribute(attributeLocator,variableName)
Getsthevalueofanelementattribute.Thevalueoftheattributemaydifferacrossbrowsers(thisis
thecaseforthe"style"attribute,forexample).
Arguments:
attributeLocatoranelementlocatorfollowedbyan@signandthenthenameofthe
attribute,e.g."foo@bar"
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
thevalueofthespecifiedattribute
RelatedAssertions,automaticallygenerated:
assertAttribute(attributeLocator,pattern)
assertNotAttribute(attributeLocator,pattern)
verifyAttribute(attributeLocator,pattern)
verifyNotAttribute(attributeLocator,pattern)
waitForAttribute(attributeLocator,pattern)
waitForNotAttribute(attributeLocator,pattern)
storeAttributeFromAllWindows(attributeName,variableName)
ReturnsanarrayofJavaScriptpropertyvaluesfromallknownwindowshavingone.
Arguments:
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

24/47

14/8/2015

SeleniumReference

attributeNamenameofanattributeonthewindows
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
thesetofvaluesofthisattributefromallknownwindows.
RelatedAssertions,automaticallygenerated:
assertAttributeFromAllWindows(attributeName,pattern)
assertNotAttributeFromAllWindows(attributeName,pattern)
verifyAttributeFromAllWindows(attributeName,pattern)
verifyNotAttributeFromAllWindows(attributeName,pattern)
waitForAttributeFromAllWindows(attributeName,pattern)
waitForNotAttributeFromAllWindows(attributeName,pattern)
storeBodyText(variableName)
Getstheentiretextofthepage.
Returns:
theentiretextofthepage
RelatedAssertions,automaticallygenerated:
assertBodyText(pattern)
assertNotBodyText(pattern)
verifyBodyText(pattern)
verifyNotBodyText(pattern)
waitForBodyText(pattern)
waitForNotBodyText(pattern)
storeConfirmation(variableName)
RetrievesthemessageofaJavaScriptconfirmationdialoggeneratedduringthepreviousaction.
Bydefault,theconfirmfunctionwillreturntrue,havingthesameeffectasmanuallyclickingOK.
ThiscanbechangedbypriorexecutionofthechooseCancelOnNextConfirmationcommand.
IfanconfirmationisgeneratedbutyoudonotconsumeitwithgetConfirmation,thenextSelenium
actionwillfail.
NOTE:underSelenium,JavaScriptconfirmationswillNOTpopupavisibledialog.
NOTE:SeleniumdoesNOTsupportJavaScriptconfirmationsthataregeneratedinapage's
onload()eventhandler.InthiscaseavisibledialogWILLbegeneratedandSeleniumwillhang
untilyoumanuallyclickOK.
Returns:
themessageofthemostrecentJavaScriptconfirmationdialog
RelatedAssertions,automaticallygenerated:
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

25/47

14/8/2015

SeleniumReference

assertConfirmation(pattern)
assertNotConfirmation(pattern)
verifyConfirmation(pattern)
verifyNotConfirmation(pattern)
waitForConfirmation(pattern)
waitForNotConfirmation(pattern)
storeCookie(variableName)
Returnallcookiesofthecurrentpageundertest.
Returns:
allcookiesofthecurrentpageundertest
RelatedAssertions,automaticallygenerated:
assertCookie(pattern)
assertNotCookie(pattern)
verifyCookie(pattern)
verifyNotCookie(pattern)
waitForCookie(pattern)
waitForNotCookie(pattern)
storeCookieByName(name,variableName)
Returnsthevalueofthecookiewiththespecifiedname,orthrowsanerrorifthecookieisnot
present.
Arguments:
namethenameofthecookie
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
thevalueofthecookie
RelatedAssertions,automaticallygenerated:
assertCookieByName(name,pattern)
assertNotCookieByName(name,pattern)
verifyCookieByName(name,pattern)
verifyNotCookieByName(name,pattern)
waitForCookieByName(name,pattern)
waitForNotCookieByName(name,pattern)
storeCursorPosition(locator,variableName)
Retrievesthetextcursorpositioninthegiveninputelementortextareabeware,thismaynotwork
perfectlyonallbrowsers.
Specifically,ifthecursor/selectionhasbeenclearedbyJavaScript,thiscommandwilltendto
returnthepositionofthelastlocationofthecursor,eventhoughthecursorisnowgonefromthe
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

26/47

14/8/2015

SeleniumReference

page.ThisisfiledasSEL243.
Thismethodwillfailifthespecifiedelementisn'taninputelementortextarea,orthereisnocursor
intheelement.
Arguments:
locatoranelementlocatorpointingtoaninputelementortextarea
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
thenumericalpositionofthecursorinthefield
RelatedAssertions,automaticallygenerated:
assertCursorPosition(locator,pattern)
assertNotCursorPosition(locator,pattern)
verifyCursorPosition(locator,pattern)
verifyNotCursorPosition(locator,pattern)
waitForCursorPosition(locator,pattern)
waitForNotCursorPosition(locator,pattern)
storeElementHeight(locator,variableName)
Retrievestheheightofanelement
Arguments:
locatoranelementlocatorpointingtoanelement
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
heightofanelementinpixels
RelatedAssertions,automaticallygenerated:
assertElementHeight(locator,pattern)
assertNotElementHeight(locator,pattern)
verifyElementHeight(locator,pattern)
verifyNotElementHeight(locator,pattern)
waitForElementHeight(locator,pattern)
waitForNotElementHeight(locator,pattern)
storeElementIndex(locator,variableName)
Gettherelativeindexofanelementtoitsparent(startingfrom0).Thecommentnodeandempty
textnodewillbeignored.
Arguments:
locatoranelementlocatorpointingtoanelement
variableNamethenameofavariableinwhichtheresultistobestored.
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

27/47

14/8/2015

SeleniumReference

Returns:
ofrelativeindexoftheelementtoitsparent(startingfrom0)
RelatedAssertions,automaticallygenerated:
assertElementIndex(locator,pattern)
assertNotElementIndex(locator,pattern)
verifyElementIndex(locator,pattern)
verifyNotElementIndex(locator,pattern)
waitForElementIndex(locator,pattern)
waitForNotElementIndex(locator,pattern)
storeElementPositionLeft(locator,variableName)
Retrievesthehorizontalpositionofanelement
Arguments:
locatoranelementlocatorpointingtoanelementORanelementitself
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
ofpixelsfromtheedgeoftheframe.
RelatedAssertions,automaticallygenerated:
assertElementPositionLeft(locator,pattern)
assertNotElementPositionLeft(locator,pattern)
verifyElementPositionLeft(locator,pattern)
verifyNotElementPositionLeft(locator,pattern)
waitForElementPositionLeft(locator,pattern)
waitForNotElementPositionLeft(locator,pattern)
storeElementPositionTop(locator,variableName)
Retrievestheverticalpositionofanelement
Arguments:
locatoranelementlocatorpointingtoanelementORanelementitself
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
ofpixelsfromtheedgeoftheframe.
RelatedAssertions,automaticallygenerated:
assertElementPositionTop(locator,pattern)
assertNotElementPositionTop(locator,pattern)
verifyElementPositionTop(locator,pattern)
verifyNotElementPositionTop(locator,pattern)
waitForElementPositionTop(locator,pattern)
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

28/47

14/8/2015

SeleniumReference

waitForNotElementPositionTop(locator,pattern)
storeElementWidth(locator,variableName)
Retrievesthewidthofanelement
Arguments:
locatoranelementlocatorpointingtoanelement
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
widthofanelementinpixels
RelatedAssertions,automaticallygenerated:
assertElementWidth(locator,pattern)
assertNotElementWidth(locator,pattern)
verifyElementWidth(locator,pattern)
verifyNotElementWidth(locator,pattern)
waitForElementWidth(locator,pattern)
waitForNotElementWidth(locator,pattern)
storeEval(script,variableName)
GetstheresultofevaluatingthespecifiedJavaScriptsnippet.Thesnippetmayhavemultiplelines,
butonlytheresultofthelastlinewillbereturned.
Notethat,bydefault,thesnippetwillruninthecontextofthe"selenium"objectitself,sothiswill
refertotheSeleniumobject.Usewindowtorefertothewindowofyourapplication,e.g.
window.document.getElementById('foo')

Ifyouneedtousealocatortorefertoasingleelementinyourapplicationpage,youcanuse
this.browserbot.findElement("id=foo")where"id=foo"isyourlocator.
Arguments:
scripttheJavaScriptsnippettorun
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
theresultsofevaluatingthesnippet
RelatedAssertions,automaticallygenerated:
assertEval(script,pattern)
assertNotEval(script,pattern)
verifyEval(script,pattern)
verifyNotEval(script,pattern)
waitForEval(script,pattern)
waitForNotEval(script,pattern)
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

29/47

14/8/2015

SeleniumReference

storeExpression(expression,variableName)
Returnsthespecifiedexpression.
ThisisusefulbecauseofJavaScriptpreprocessing.Itisusedtogeneratecommandslike
assertExpressionandwaitForExpression.
Arguments:
expressionthevaluetoreturn
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
thevaluepassedin
RelatedAssertions,automaticallygenerated:
assertExpression(expression,pattern)
assertNotExpression(expression,pattern)
verifyExpression(expression,pattern)
verifyNotExpression(expression,pattern)
waitForExpression(expression,pattern)
waitForNotExpression(expression,pattern)
storeHtmlSource(variableName)
ReturnstheentireHTMLsourcebetweentheopeningandclosing"html"tags.
Returns:
theentireHTMLsource
RelatedAssertions,automaticallygenerated:
assertHtmlSource(pattern)
assertNotHtmlSource(pattern)
verifyHtmlSource(pattern)
verifyNotHtmlSource(pattern)
waitForHtmlSource(pattern)
waitForNotHtmlSource(pattern)
storeLocation(variableName)
GetstheabsoluteURLofthecurrentpage.
Returns:
theabsoluteURLofthecurrentpage
RelatedAssertions,automaticallygenerated:
assertLocation(pattern)
assertNotLocation(pattern)
verifyLocation(pattern)
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

30/47

14/8/2015

SeleniumReference

verifyNotLocation(pattern)
waitForLocation(pattern)
waitForNotLocation(pattern)
storeMouseSpeed(variableName)
Returnsthenumberofpixelsbetween"mousemove"eventsduringdragAndDropcommands
(default=10).
Returns:
thenumberofpixelsbetween"mousemove"eventsduringdragAndDropcommands
(default=10)
RelatedAssertions,automaticallygenerated:
assertMouseSpeed(pattern)
assertNotMouseSpeed(pattern)
verifyMouseSpeed(pattern)
verifyNotMouseSpeed(pattern)
waitForMouseSpeed(pattern)
waitForNotMouseSpeed(pattern)
storePrompt(variableName)
RetrievesthemessageofaJavaScriptquestionpromptdialoggeneratedduringthepreviousaction.
SuccessfulhandlingofthepromptrequirespriorexecutionoftheanswerOnNextPromptcommand.
Ifapromptisgeneratedbutyoudonotget/verifyit,thenextSeleniumactionwillfail.
NOTE:underSelenium,JavaScriptpromptswillNOTpopupavisibledialog.
NOTE:SeleniumdoesNOTsupportJavaScriptpromptsthataregeneratedinapage'sonload()
eventhandler.InthiscaseavisibledialogWILLbegeneratedandSeleniumwillhanguntil
someonemanuallyclicksOK.
Returns:
themessageofthemostrecentJavaScriptquestionprompt
RelatedAssertions,automaticallygenerated:
assertPrompt(pattern)
assertNotPrompt(pattern)
verifyPrompt(pattern)
verifyNotPrompt(pattern)
waitForPrompt(pattern)
waitForNotPrompt(pattern)
storeSelectedId(selectLocator,variableName)
GetsoptionelementIDforselectedoptioninthespecifiedselectelement.
Arguments:
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

31/47

14/8/2015

SeleniumReference

selectLocatoranelementlocatoridentifyingadropdownmenu
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
theselectedoptionIDinthespecifiedselectdropdown
RelatedAssertions,automaticallygenerated:
assertSelectedId(selectLocator,pattern)
assertNotSelectedId(selectLocator,pattern)
verifySelectedId(selectLocator,pattern)
verifyNotSelectedId(selectLocator,pattern)
waitForSelectedId(selectLocator,pattern)
waitForNotSelectedId(selectLocator,pattern)
storeSelectedIds(selectLocator,variableName)
GetsalloptionelementIDsforselectedoptionsinthespecifiedselectormultiselectelement.
Arguments:
selectLocatoranelementlocatoridentifyingadropdownmenu
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
anarrayofallselectedoptionIDsinthespecifiedselectdropdown
RelatedAssertions,automaticallygenerated:
assertSelectedIds(selectLocator,pattern)
assertNotSelectedIds(selectLocator,pattern)
verifySelectedIds(selectLocator,pattern)
verifyNotSelectedIds(selectLocator,pattern)
waitForSelectedIds(selectLocator,pattern)
waitForNotSelectedIds(selectLocator,pattern)
storeSelectedIndex(selectLocator,variableName)
Getsoptionindex(optionnumber,startingat0)forselectedoptioninthespecifiedselectelement.
Arguments:
selectLocatoranelementlocatoridentifyingadropdownmenu
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
theselectedoptionindexinthespecifiedselectdropdown
RelatedAssertions,automaticallygenerated:
assertSelectedIndex(selectLocator,pattern)
assertNotSelectedIndex(selectLocator,pattern)
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

32/47

14/8/2015

SeleniumReference

verifySelectedIndex(selectLocator,pattern)
verifyNotSelectedIndex(selectLocator,pattern)
waitForSelectedIndex(selectLocator,pattern)
waitForNotSelectedIndex(selectLocator,pattern)
storeSelectedIndexes(selectLocator,variableName)
Getsalloptionindexes(optionnumber,startingat0)forselectedoptionsinthespecifiedselector
multiselectelement.
Arguments:
selectLocatoranelementlocatoridentifyingadropdownmenu
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
anarrayofallselectedoptionindexesinthespecifiedselectdropdown
RelatedAssertions,automaticallygenerated:
assertSelectedIndexes(selectLocator,pattern)
assertNotSelectedIndexes(selectLocator,pattern)
verifySelectedIndexes(selectLocator,pattern)
verifyNotSelectedIndexes(selectLocator,pattern)
waitForSelectedIndexes(selectLocator,pattern)
waitForNotSelectedIndexes(selectLocator,pattern)
storeSelectedLabel(selectLocator,variableName)
Getsoptionlabel(visibletext)forselectedoptioninthespecifiedselectelement.
Arguments:
selectLocatoranelementlocatoridentifyingadropdownmenu
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
theselectedoptionlabelinthespecifiedselectdropdown
RelatedAssertions,automaticallygenerated:
assertSelectedLabel(selectLocator,pattern)
assertNotSelectedLabel(selectLocator,pattern)
verifySelectedLabel(selectLocator,pattern)
verifyNotSelectedLabel(selectLocator,pattern)
waitForSelectedLabel(selectLocator,pattern)
waitForNotSelectedLabel(selectLocator,pattern)
storeSelectedLabels(selectLocator,variableName)
Getsalloptionlabels(visibletext)forselectedoptionsinthespecifiedselectormultiselect
element.
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

33/47

14/8/2015

SeleniumReference

Arguments:
selectLocatoranelementlocatoridentifyingadropdownmenu
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
anarrayofallselectedoptionlabelsinthespecifiedselectdropdown
RelatedAssertions,automaticallygenerated:
assertSelectedLabels(selectLocator,pattern)
assertNotSelectedLabels(selectLocator,pattern)
verifySelectedLabels(selectLocator,pattern)
verifyNotSelectedLabels(selectLocator,pattern)
waitForSelectedLabels(selectLocator,pattern)
waitForNotSelectedLabels(selectLocator,pattern)
storeSelectedValue(selectLocator,variableName)
Getsoptionvalue(valueattribute)forselectedoptioninthespecifiedselectelement.
Arguments:
selectLocatoranelementlocatoridentifyingadropdownmenu
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
theselectedoptionvalueinthespecifiedselectdropdown
RelatedAssertions,automaticallygenerated:
assertSelectedValue(selectLocator,pattern)
assertNotSelectedValue(selectLocator,pattern)
verifySelectedValue(selectLocator,pattern)
verifyNotSelectedValue(selectLocator,pattern)
waitForSelectedValue(selectLocator,pattern)
waitForNotSelectedValue(selectLocator,pattern)
storeSelectedValues(selectLocator,variableName)
Getsalloptionvalues(valueattributes)forselectedoptionsinthespecifiedselectormultiselect
element.
Arguments:
selectLocatoranelementlocatoridentifyingadropdownmenu
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
anarrayofallselectedoptionvaluesinthespecifiedselectdropdown
RelatedAssertions,automaticallygenerated:
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

34/47

14/8/2015

SeleniumReference

assertSelectedValues(selectLocator,pattern)
assertNotSelectedValues(selectLocator,pattern)
verifySelectedValues(selectLocator,pattern)
verifyNotSelectedValues(selectLocator,pattern)
waitForSelectedValues(selectLocator,pattern)
waitForNotSelectedValues(selectLocator,pattern)
storeSelectOptions(selectLocator,variableName)
Getsalloptionlabelsinthespecifiedselectdropdown.
Arguments:
selectLocatoranelementlocatoridentifyingadropdownmenu
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
anarrayofalloptionlabelsinthespecifiedselectdropdown
RelatedAssertions,automaticallygenerated:
assertSelectOptions(selectLocator,pattern)
assertNotSelectOptions(selectLocator,pattern)
verifySelectOptions(selectLocator,pattern)
verifyNotSelectOptions(selectLocator,pattern)
waitForSelectOptions(selectLocator,pattern)
waitForNotSelectOptions(selectLocator,pattern)
storeSpeed(variableName)
Getexecutionspeed(i.e.,getthemillisecondlengthofthedelayfollowingeachselenium
operation).Bydefault,thereisnosuchdelay,i.e.,thedelayis0milliseconds.SeealsosetSpeed.
Returns:
theexecutionspeedinmilliseconds.
RelatedAssertions,automaticallygenerated:
assertSpeed(pattern)
assertNotSpeed(pattern)
verifySpeed(pattern)
verifyNotSpeed(pattern)
waitForSpeed(pattern)
waitForNotSpeed(pattern)
storeTable(tableCellAddress,variableName)
Getsthetextfromacellofatable.ThecellAddresssyntaxtableLocator.row.column,whererow
andcolumnstartat0.
Arguments:
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

35/47

14/8/2015

SeleniumReference

tableCellAddressacelladdress,e.g."foo.1.4"
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
thetextfromthespecifiedcell
RelatedAssertions,automaticallygenerated:
assertTable(tableCellAddress,pattern)
assertNotTable(tableCellAddress,pattern)
verifyTable(tableCellAddress,pattern)
verifyNotTable(tableCellAddress,pattern)
waitForTable(tableCellAddress,pattern)
waitForNotTable(tableCellAddress,pattern)
storeText(locator,variableName)
Getsthetextofanelement.Thisworksforanyelementthatcontainstext.Thiscommanduses
eitherthetextContent(Mozillalikebrowsers)ortheinnerText(IElikebrowsers)oftheelement,
whichistherenderedtextshowntotheuser.
Arguments:
locatoranelementlocator
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
thetextoftheelement
RelatedAssertions,automaticallygenerated:
assertText(locator,pattern)
assertNotText(locator,pattern)
verifyText(locator,pattern)
verifyNotText(locator,pattern)
waitForText(locator,pattern)
waitForNotText(locator,pattern)
storeTitle(variableName)
Getsthetitleofthecurrentpage.
Returns:
thetitleofthecurrentpage
RelatedAssertions,automaticallygenerated:
assertTitle(pattern)
assertNotTitle(pattern)
verifyTitle(pattern)
verifyNotTitle(pattern)
waitForTitle(pattern)
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

36/47

14/8/2015

SeleniumReference

waitForNotTitle(pattern)
storeValue(locator,variableName)
Getsthe(whitespacetrimmed)valueofaninputfield(oranythingelsewithavalueparameter).
Forcheckbox/radioelements,thevaluewillbe"on"or"off"dependingonwhethertheelementis
checkedornot.
Arguments:
locatoranelementlocator
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
theelementvalue,or"on/off"forcheckbox/radioelements
RelatedAssertions,automaticallygenerated:
assertValue(locator,pattern)
assertNotValue(locator,pattern)
verifyValue(locator,pattern)
verifyNotValue(locator,pattern)
waitForValue(locator,pattern)
waitForNotValue(locator,pattern)
storeWhetherThisFrameMatchFrameExpression(currentFrameString,target,variableName)
Determinewhethercurrent/locatoridentifytheframecontainingthisrunningcode.
Thisisusefulinproxyinjectionmode,wherethiscoderunsineverybrowserframeandwindow,
andsometimestheseleniumserverneedstoidentifythe"current"frame.Inthiscase,whenthetest
callsselectFrame,thisroutineiscalledforeachframetofigureoutwhichonehasbeenselected.
Theselectedframewillreturntrue,whileallotherswillreturnfalse.
Arguments:
currentFrameStringstartingframe
targetnewframe(whichmightberelativetothecurrentone)
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
trueifthenewframeisthiscode'swindow
RelatedAssertions,automaticallygenerated:
assertWhetherThisFrameMatchFrameExpression(currentFrameString,target)
assertNotWhetherThisFrameMatchFrameExpression(currentFrameString,target)
verifyWhetherThisFrameMatchFrameExpression(currentFrameString,target)
verifyNotWhetherThisFrameMatchFrameExpression(currentFrameString,target)
waitForWhetherThisFrameMatchFrameExpression(currentFrameString,target)
waitForNotWhetherThisFrameMatchFrameExpression(currentFrameString,target)
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

37/47

14/8/2015

SeleniumReference

storeWhetherThisWindowMatchWindowExpression(currentWindowString,target,
variableName)
DeterminewhethercurrentWindowStringplustargetidentifythewindowcontainingthisrunning
code.
Thisisusefulinproxyinjectionmode,wherethiscoderunsineverybrowserframeandwindow,
andsometimestheseleniumserverneedstoidentifythe"current"window.Inthiscase,whenthe
testcallsselectWindow,thisroutineiscalledforeachwindowtofigureoutwhichonehasbeen
selected.Theselectedwindowwillreturntrue,whileallotherswillreturnfalse.
Arguments:
currentWindowStringstartingwindow
targetnewwindow(whichmightberelativetothecurrentone,e.g.,"_parent")
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
trueifthenewwindowisthiscode'swindow
RelatedAssertions,automaticallygenerated:
assertWhetherThisWindowMatchWindowExpression(currentWindowString,target)
assertNotWhetherThisWindowMatchWindowExpression(currentWindowString,target)
verifyWhetherThisWindowMatchWindowExpression(currentWindowString,target)
verifyNotWhetherThisWindowMatchWindowExpression(currentWindowString,target)
waitForWhetherThisWindowMatchWindowExpression(currentWindowString,target)
waitForNotWhetherThisWindowMatchWindowExpression(currentWindowString,target)
storeXpathCount(xpath,variableName)
Returnsthenumberofnodesthatmatchthespecifiedxpath,eg."//table"wouldgivethenumberof
tables.
Arguments:
xpaththexpathexpressiontoevaluate.doNOTwrapthisexpressionina'count()'function
wewilldothatforyou.
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
thenumberofnodesthatmatchthespecifiedxpath
RelatedAssertions,automaticallygenerated:
assertXpathCount(xpath,pattern)
assertNotXpathCount(xpath,pattern)
verifyXpathCount(xpath,pattern)
verifyNotXpathCount(xpath,pattern)
waitForXpathCount(xpath,pattern)
waitForNotXpathCount(xpath,pattern)
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

38/47

14/8/2015

SeleniumReference

storeAlertPresent(variableName)
Hasanalertoccurred?
Thisfunctionneverthrowsanexception
Returns:
trueifthereisanalert
RelatedAssertions,automaticallygenerated:
assertAlertPresent()
assertAlertNotPresent()
verifyAlertPresent()
verifyAlertNotPresent()
waitForAlertPresent()
waitForAlertNotPresent()
storeChecked(locator,variableName)
Getswhetheratogglebutton(checkbox/radio)ischecked.Failsifthespecifiedelementdoesn't
existorisn'tatogglebutton.
Arguments:
locatoranelementlocatorpointingtoacheckboxorradiobutton
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
trueifthecheckboxischecked,falseotherwise
RelatedAssertions,automaticallygenerated:
assertChecked(locator)
assertNotChecked(locator)
verifyChecked(locator)
verifyNotChecked(locator)
waitForChecked(locator)
waitForNotChecked(locator)
storeConfirmationPresent(variableName)
Hasconfirm()beencalled?
Thisfunctionneverthrowsanexception
Returns:
trueifthereisapendingconfirmation
RelatedAssertions,automaticallygenerated:
assertConfirmationPresent()
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

39/47

14/8/2015

SeleniumReference

assertConfirmationNotPresent()
verifyConfirmationPresent()
verifyConfirmationNotPresent()
waitForConfirmationPresent()
waitForConfirmationNotPresent()
storeCookiePresent(name,variableName)
Returnstrueifacookiewiththespecifiednameispresent,orfalseotherwise.
Arguments:
namethenameofthecookie
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
trueifacookiewiththespecifiednameispresent,orfalseotherwise.
RelatedAssertions,automaticallygenerated:
assertCookiePresent(name)
assertCookieNotPresent(name)
verifyCookiePresent(name)
verifyCookieNotPresent(name)
waitForCookiePresent(name)
waitForCookieNotPresent(name)
storeEditable(locator,variableName)
Determineswhetherthespecifiedinputelementiseditable,iehasn'tbeendisabled.Thismethod
willfailifthespecifiedelementisn'taninputelement.
Arguments:
locatoranelementlocator
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
trueiftheinputelementiseditable,falseotherwise
RelatedAssertions,automaticallygenerated:
assertEditable(locator)
assertNotEditable(locator)
verifyEditable(locator)
verifyNotEditable(locator)
waitForEditable(locator)
waitForNotEditable(locator)
storeElementPresent(locator,variableName)
Verifiesthatthespecifiedelementissomewhereonthepage.
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

40/47

14/8/2015

SeleniumReference

Arguments:
locatoranelementlocator
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
trueiftheelementispresent,falseotherwise
RelatedAssertions,automaticallygenerated:
assertElementPresent(locator)
assertElementNotPresent(locator)
verifyElementPresent(locator)
verifyElementNotPresent(locator)
waitForElementPresent(locator)
waitForElementNotPresent(locator)
storeOrdered(locator1,locator2,variableName)
CheckifthesetwoelementshavesameparentandareorderedsiblingsintheDOM.Twosame
elementswillnotbeconsideredordered.
Arguments:
locator1anelementlocatorpointingtothefirstelement
locator2anelementlocatorpointingtothesecondelement
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
trueifelement1istheprevioussiblingofelement2,falseotherwise
RelatedAssertions,automaticallygenerated:
assertOrdered(locator1,locator2)
assertNotOrdered(locator1,locator2)
verifyOrdered(locator1,locator2)
verifyNotOrdered(locator1,locator2)
waitForOrdered(locator1,locator2)
waitForNotOrdered(locator1,locator2)
storePromptPresent(variableName)
Hasapromptoccurred?
Thisfunctionneverthrowsanexception
Returns:
trueifthereisapendingprompt
RelatedAssertions,automaticallygenerated:
assertPromptPresent()
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

41/47

14/8/2015

SeleniumReference

assertPromptNotPresent()
verifyPromptPresent()
verifyPromptNotPresent()
waitForPromptPresent()
waitForPromptNotPresent()
storeSomethingSelected(selectLocator,variableName)
Determineswhethersomeoptioninadropdownmenuisselected.
Arguments:
selectLocatoranelementlocatoridentifyingadropdownmenu
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
trueifsomeoptionhasbeenselected,falseotherwise
RelatedAssertions,automaticallygenerated:
assertSomethingSelected(selectLocator)
assertNotSomethingSelected(selectLocator)
verifySomethingSelected(selectLocator)
verifyNotSomethingSelected(selectLocator)
waitForSomethingSelected(selectLocator)
waitForNotSomethingSelected(selectLocator)
storeTextPresent(pattern,variableName)
Verifiesthatthespecifiedtextpatternappearssomewhereontherenderedpageshowntotheuser.
Arguments:
patternapatterntomatchwiththetextofthepage
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
trueifthepatternmatchesthetext,falseotherwise
RelatedAssertions,automaticallygenerated:
assertTextPresent(pattern)
assertTextNotPresent(pattern)
verifyTextPresent(pattern)
verifyTextNotPresent(pattern)
waitForTextPresent(pattern)
waitForTextNotPresent(pattern)
storeVisible(locator,variableName)
Determinesifthespecifiedelementisvisible.Anelementcanberenderedinvisiblebysettingthe
CSS"visibility"propertyto"hidden",orthe"display"propertyto"none",eitherfortheelement
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

42/47

14/8/2015

SeleniumReference

itselforoneifitsancestors.Thismethodwillfailiftheelementisnotpresent.
Arguments:
locatoranelementlocator
variableNamethenameofavariableinwhichtheresultistobestored.
Returns:
trueifthespecifiedelementisvisible,falseotherwise
RelatedAssertions,automaticallygenerated:
assertVisible(locator)
assertNotVisible(locator)
verifyVisible(locator)
verifyNotVisible(locator)
waitForVisible(locator)
waitForNotVisible(locator)

ParameterconstructionandVariables
AllSeleniumcommandparameterscanbeconstructedusingbothsimplevariable
substitutionaswellasfulljavascript.Bothofthesemechanismscanaccesspreviouslystored
variables,butdosousingdifferentsyntax.
StoredVariables
Thecommandsstore,storeValueandstoreTextcanbeusedtostoreavariablevalueforlater
access.Internally,thesevariablesarestoredinamapcalled"storedVars",withvalueskeyed
bythevariablename.Thesecommandsaredocumentedinthecommandreference.
Variablesubstitution
Variablesubstitutionprovidesasimplewaytoincludeapreviouslystoredvariableina
commandparameter.Thisisasimplemechanism,bywhichthevariabletosubstituteis
indicatedby${variableName}.Multiplevariablescanbesubstituted,andintermixedwith
statictext.
Example:
store

Mr

title

storeValue nameField

surname

store
type

fullname
Fullnameis:${fullname}

${title}${surname}
textElement

Javascriptevaluation
Javascriptevaluationprovidesthefullpowerofjavascriptinconstructingacommand
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

43/47

14/8/2015

SeleniumReference

parameter.Tousethismechanism,theentireparametervaluemustbeprefixedby
'javascript{'withatrailing'}'.Thetextinsidethebracesisevaluatedasajavascript
expression,andcanaccesspreviouslystoredvariablesusingthestoredVarsmapdetailed
above.Notethatvariablesubstitutioncannotbecombinedwithjavascriptevaluation.
Example:
store javascript{'merchant' merchantId
+(new
Date()).getTime()}
type textElement

javascript{storedVars['merchantId'].toUpperCase()}

WhitespaceRules
HTMLautomaticallynormalizeswhitespacewithinelements,ignoringleading/trailing
spacesandconvertingextraspaces,tabsandnewlinesintoasinglespace.WhenSelenium
readstextoutofthepage,itattemptstoduplicatethisbehavior,soyoucanignoreallthe
tabsandnewlinesinyourHTMLanddoassertionsbasedonhowthetextlooksinthe
browserwhenrendered.Wedothisbyreplacingallnonvisiblewhitespace(includingthe
nonbreakingspace"&nbsp")withasinglespace.Allvisiblenewlines(<br>,<p>,and
<pre>formattednewlines)shouldbepreserved.
WeusethesamenormalizationlogiconthetextofHTMLSelenesetestcasetables.Thishas
anumberofadvantages.First,youdon'tneedtolookattheHTMLsourceofthepageto
figureoutwhatyourassertionsshouldbe"&nbsp"symbolsareinvisibletotheenduser,
andsoyoushouldn'thavetoworryaboutthemwhenwritingSelenesetests.(Youdon'tneed
toput"&nbsp"markersinyourtestcasetoassertTextonafieldthatcontains"&nbsp".)
YoumayalsoputextranewlinesandspacesinyourSelenese<td>tagssinceweusethe
samenormalizationlogiconthetestcaseaswedoonthetext,wecanensurethatassertions
andtheextractedtextwillmatchexactly.
Thiscreatesabitofaproblemonthoserareoccasionswhenyoureallywant/needtoinsert
extrawhitespaceinyourtestcase.Forexample,youmayneedtotypetextinafieldlike
this:"foo".Butifyousimplywrite<td>foo</td>inyourSelenesetestcase,we'llreplace
yourextraspaceswithjustonespace.
Thisproblemhasasimpleworkaround.We'vedefinedavariableinSelenese,${space},
whosevalueisasinglespace.Youcanuse${space}toinsertaspacethatwon'tbe
automaticallytrimmed,likethis:<td>foo${space}${space}${space}</td>.We'vealso
includedavariable${nbsp},thatyoucanusetoinsertanonbreakingspace.
NotethatXPathsdonotnormalizewhitespacethewaywedo.IfyouneedtowriteanXPath
like//div[text()="helloworld"]buttheHTMLofthelinkisreally"hello&nbspworld",
you'llneedtoinsertareal"&nbsp"intoyourSelenesetestcasetogetittomatch,likethis:
//div[text()="hello${nbsp}world"].

ExtendingSelenium
ItcanbequitesimpletoextendSelenium,addingyourownactions,assertionsandlocator
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

44/47

14/8/2015

SeleniumReference

strategies.ThisisdonewithjavascriptbyaddingmethodstotheSeleniumobjectprototype,
andthePageBotobjectprototype.Onstartup,Seleniumwillautomaticallylookthrough
methodsontheseprototypes,usingnamepatternstorecognisewhichonesareactions,
assertionsandlocators.
ThefollowingexamplestrytogiveanindicationofhowSeleniumcanbeextendedwith
javascript.
Actions
AlldoFoomethodsontheSeleniumprototypeareaddedasactions.Foreachactionfoo
thereisalsoanactionfooAndWaitregistered.Anactionmethodcantakeupto2parameters,
whichwillbepassedthesecondandthirdcolumnvaluesinthetest.
Example:Adda"typeRepeated"actiontoSelenium,whichtypesthetexttwiceintoatext
box.

Selenium.prototype.doTypeRepeated=function(locator,text){
//Alllocatorstrategiesareautomaticallyhandledby"findElement"
varelement=this.page().findElement(locator);
//Createthetexttotype
varvalueToType=text+text;
//Replacetheelementtextwiththenewtext
this.page().replaceText(element,valueToType);
};

Accessors/Assertions
AllgetFooandisFoomethodsontheSeleniumprototypeareaddedasaccessors(storeFoo).
ForeachaccessorthereisanassertFoo,verifyFooandwaitForFooregistered.Anassert
methodcantakeupto2parameters,whichwillbepassedthesecondandthirdcolumn
valuesinthetest.Youcanalsodefineyourownassertionsliterallyassimple"assert"
methods,whichwillalsoautogenerate"verify"and"waitFor"commands.
Example:AddavalueRepeatedassertion,thatmakessurethattheelementvalueconsistsof
thesuppliedtextrepeated.The2commandsthatwouldbeavailableintestswouldbe
assertValueRepeatedandverifyValueRepeated.

Selenium.prototype.assertValueRepeated=function(locator,text){
//Alllocatorstrategiesareautomaticallyhandledby"findElement"
varelement=this.page().findElement(locator);
//Createthetexttoverify
varexpectedValue=text+text;
//Gettheactualelementvalue
varactualValue=element.value;
//Makesuretheactualvaluematchestheexpected
Assert.matches(expectedValue,actualValue);
};

http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

45/47

14/8/2015

SeleniumReference

AutomaticavailabilityofstoreFoo,assertFoo,assertNotFoo,waitForFooandwaitForNotFoofor
everygetFoo
AllgetFooandisFoomethodsontheSeleniumprototypeautomaticallyresultinthe
availabilityofstoreFoo,assertFoo,assertNotFoo,verifyFoo,verifyNotFoo,waitForFoo,and
waitForNotFoocommands.
Example,ifyouaddagetTextLength()method,thefollowingcommandswillautomatically
beavailable:storeTextLength,assertTextLength,assertNotTextLength,verifyTextLength,
verifyNotTextLength,waitForTextLength,andwaitForNotTextLengthcommands.

Selenium.prototype.getTextLength=function(locator,text){
returnthis.getText(locator).length;
};

AlsonotethattheassertValueRepeatedmethoddescribedabovecouldhavebeen
implementedusingisValueRepeated,withtheaddedbenefitofalsoautomaticallygetting
assertNotValueRepeated,storeValueRepeated,waitForValueRepeatedand
waitForNotValueRepeated.
LocatorStrategies
AlllocateElementByFoomethodsonthePageBotprototypeareaddedaslocatorstrategies.
Alocatorstrategytakes2parameters,thefirstbeingthelocatorstring(minustheprefix),
andthesecondbeingthedocumentinwhichtosearch.
Example:Adda"valuerepeated="locator,thatfindsthefirstelementavalueattributeequal
tothethesuppliedvaluerepeated.

//The"inDocument"isathedocumentyouaresearching.
PageBot.prototype.locateElementByValueRepeated=function(text,inDocument){
//Createthetexttosearchfor
varexpectedValue=text+text;
//Loopthroughallelements,lookingforonesthathave
//avalue===ourexpectedvalue
varallElements=inDocument.getElementsByTagName("*");
for(vari=0;i<allElements.length;i++){
vartestElement=allElements[i];
if(testElement.value&&testElement.value===expectedValue){
returntestElement;
}
}
returnnull;
};

userextensions.js
Bydefault,Seleniumlooksforafilecalled"userextensions.js",andloadsthejavascript
codefoundinthatfile.Thisfileprovidesaconvenientlocationforaddingfeaturesto
Selenium,withoutneedingtomodifythecoreSeleniumsources.
Inthestandarddistibution,thisfiledoesnotexist.Userscancreatethisfileandplacetheir
http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

46/47

14/8/2015

SeleniumReference

extensioncodeinthiscommonlocation,removingtheneedtomodifytheSeleniumsources,
andhopefullyassistingwiththeupgradeprocess.

http://release.seleniumhq.org/seleniumcore/1.0.1/reference.html

47/47

Das könnte Ihnen auch gefallen