Anda di halaman 1dari 17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation

editthispage

BrowserAutomation

Navigation

Projects

searchselenium:

Download

Documentation

Go
Support

About

ProgrammingLanguagePreference

SeleniumDocumentation
previous| next

Selenium1(SeleniumRC)
Introduction

TableOfContents
Selenium1(SeleniumRC)
Introduction
HowSeleniumRC
Works
Installation
FromSelenesetoa
Program
ProgrammingYourTest
LearningtheAPI
ReportingResults
AddingSomeSpiceto
YourTests
ServerOptions

AsyoucanreadinBriefHistoryofTheSeleniumProject,SeleniumRCwasthemainSelenium
projectforalongtime,beforetheWebDriver/SeleniummergebroughtupSelenium2,the
newestandmorepowerfultool.
Selenium1isstillactivelysupported(mostlyinmaintenancemode)andprovidessome
featuresthatmaynotbeavailableinSelenium2forawhile,includingsupportforseveral
languages(Java,Javascript,Ruby,PHP,Python,PerlandC#)andsupportforalmostevery
browseroutthere.

HowSeleniumRCWorks
First,wewilldescribehowthecomponentsofSeleniumRCoperateandtheroleeachplaysin
runningyourtestscripts.

RCComponents
SeleniumRCcomponentsare:
TheSeleniumServerwhichlaunchesandkillsbrowsers,interpretsandrunsthe
Selenesecommandspassedfromthetestprogram,andactsasanHTTPproxy,
interceptingandverifyingHTTPmessagespassedbetweenthebrowserandtheAUT.
Clientlibrarieswhichprovidetheinterfacebetweeneachprogramminglanguageand
theSeleniumRCServer.

SpecifyingthePathtoa
SpecificBrowser
SeleniumRC
Architecture
HandlingHTTPSand
SecurityPopups

Hereisasimplifiedarchitecturediagram....

SupportingAdditional
BrowsersandBrowser
Configurations
Troubleshooting
CommonProblems
Previoustopic
WebDriver:AdvancedUsage
Nexttopic
TestDesignConsiderations

DonatetoSelenium
withPayPal

throughsponsorship

YoucansponsortheSelenium
projectifyou'dlikesome
publicrecognitionofyour
generouscontribution.

SeleniumSponsors
Seewhosupportsthe
Seleniumproject.

ThediagramshowstheclientlibrariescommunicatewiththeServerpassingeachSelenium
commandforexecution.ThentheserverpassestheSeleniumcommandtothebrowser
usingSeleniumCoreJavaScriptcommands.Thebrowser,usingitsJavaScriptinterpreter,
executestheSeleniumcommand.ThisrunstheSeleneseactionorverificationyouspecified
inyourtestscript.

SeleniumServer
SeleniumServerreceivesSeleniumcommandsfromyourtestprogram,interpretsthem,
andreportsbacktoyourprogramtheresultsofrunningthosetests.
TheRCserverbundlesSeleniumCoreandautomaticallyinjectsitintothebrowser.This

http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

1/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation
occurswhenyourtestprogramopensthebrowser(usingaclientlibraryAPIfunction).
SeleniumCoreisaJavaScriptprogram,actuallyasetofJavaScriptfunctionswhich
interpretsandexecutesSelenesecommandsusingthebrowsersbuiltinJavaScript
interpreter.
TheServerreceivestheSelenesecommandsfromyourtestprogramusingsimpleHTTP
GET/POSTrequests.Thismeansyoucanuseanyprogramminglanguagethatcansend
HTTPrequeststoautomateSeleniumtestsonthebrowser.

ClientLibraries
TheclientlibrariesprovidetheprogrammingsupportthatallowsyoutorunSelenium
commandsfromaprogramofyourowndesign.Thereisadifferentclientlibraryforeach
supportedlanguage.ASeleniumclientlibraryprovidesaprogramminginterface(API),i.e.,
asetoffunctions,whichrunSeleniumcommandsfromyourownprogram.Withineach
interface,thereisaprogrammingfunctionthatsupportseachSelenesecommand.
TheclientlibrarytakesaSelenesecommandandpassesittotheSeleniumServerfor
processingaspecificactionortestagainsttheapplicationundertest(AUT).Theclient
libraryalsoreceivestheresultofthatcommandandpassesitbacktoyourprogram.Your
programcanreceivetheresultandstoreitintoaprogramvariableandreportitasa
successorfailure,orpossiblytakecorrectiveactionifitwasanunexpectederror.
Sotocreateatestprogram,yousimplywriteaprogramthatrunsasetofSelenium
commandsusingaclientlibraryAPI.And,optionally,ifyoualreadyhaveaSelenesetest
scriptcreatedintheSeleniumIDE,youcangeneratetheSeleniumRCcode.TheSelenium
IDEcantranslate(usingitsExportmenuitem)itsSeleniumcommandsintoaclientdrivers
APIfunctioncalls.SeetheSeleniumIDEchapterforspecificsonexportingRCcodefrom
SeleniumIDE.

Installation
InstallationisratheramisnomerforSelenium.Seleniumhasasetoflibrariesavailableinthe
programminglanguageofyourchoice.Youcoulddownloadthemfromdownloadspage
Onceyouvechosenalanguagetoworkwith,yousimplyneedto:
InstalltheSeleniumRCServer.
Setupaprogrammingprojectusingalanguagespecificclientdriver.

InstallingSeleniumServer
TheSeleniumRCserverissimplyaJavajarfile(seleniumserverstandalone<version
number>.jar),whichdoesntrequireanyspecialinstallation.Justdownloadingthezipfile
andextractingtheserverinthedesireddirectoryissufficient.

RunningSeleniumServer
Beforestartinganytestsyoumuststarttheserver.GotothedirectorywhereSelenium
RCsserverislocatedandrunthefollowingfromacommandlineconsole.
javajarseleniumserverstandalone<versionnumber>.jar
Thiscanbesimplifiedbycreatingabatchorshellexecutablefile(.batonWindowsand.sh
onLinux)containingthecommandabove.Thenmakeashortcuttothatexecutableonyour
desktopandsimplydoubleclicktheicontostarttheserver.
FortheservertorunyoullneedJavainstalledandthePATHenvironmentvariablecorrectly
configuredtorunitfromtheconsole.YoucancheckthatyouhaveJavacorrectlyinstalled
byrunningthefollowingonaconsole.
javaversion
Ifyougetaversionnumber(whichneedstobe1.5orlater),yourereadytostartusing
SeleniumRC.

UsingtheJavaClientDriver
DownloadSeleniumjavaclientdriverzipfromtheSeleniumHQdownloadspage.
Extractseleniumjava<versionnumber>.jarfile
OpenyourdesiredJavaIDE(Eclipse,NetBeans,IntelliJ,Netweaver,etc.)
Createajavaproject.
Addtheseleniumjava<versionnumber>.jarfilestoyourprojectasreferences.
Addtoyourprojectclasspaththefileseleniumjava<versionnumber>.jar.
FromSeleniumIDE,exportascripttoaJavafileandincludeitinyourJavaproject,
orwriteyourSeleniumtestinJavausingtheseleniumjavaclientAPI.TheAPIis
presentedlaterinthischapter.YoucaneitheruseJUnit,orTestNgtorunyourtest,
oryoucanwriteyourownsimplemain()program.Theseconceptsareexplainedlater
inthissection.
RunSeleniumserverfromtheconsole.
ExecuteyourtestfromtheJavaIDEorfromthecommandline.
FordetailsonJavatestprojectconfiguration,seetheAppendixsectionsConfiguring
SeleniumRCWithEclipseandConfiguringSeleniumRCWithIntellij.

UsingthePythonClientDriver
http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

2/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation
InstallSeleniumviaPIP,instructionslinkedatSeleniumHQdownloadspage
EitherwriteyourSeleniumtestinPythonorexportascriptfromSeleniumIDEtoa
pythonfile.
RunSeleniumserverfromtheconsole
ExecuteyourtestfromaconsoleoryourPythonIDE
FordetailsonPythonclientdriverconfiguration,seetheappendixPythonClientDriver
Configuration.

Usingthe.NETClientDriver
DownloadSeleniumRCfromtheSeleniumHQdownloadspage
Extractthefolder
DownloadandinstallNUnit(Note:YoucanuseNUnitasyourtestengine.Ifyoure
notfamiliaryetwithNUnit,youcanalsowriteasimplemain()functiontorunyour
testshoweverNUnitisveryusefulasatestengine.)
Openyourdesired.NetIDE(VisualStudio,SharpDevelop,MonoDevelop)
Createaclasslibrary(.dll)
AddreferencestothefollowingDLLs:nmock.dll,nunit.core.dll,nunit.framework.dll,
ThoughtWorks.Selenium.Core.dll,ThoughtWorks.Selenium.IntegrationTests.dlland
ThoughtWorks.Selenium.UnitTests.dll
WriteyourSeleniumtestina.Netlanguage(C#,VB.Net),orexportascriptfrom
SeleniumIDEtoaC#fileandcopythiscodeintotheclassfileyoujustcreated.
Writeyourownsimplemain()programoryoucanincludeNUnitinyourprojectfor
runningyourtest.Theseconceptsareexplainedlaterinthischapter.
RunSeleniumserverfromconsole
RunyourtesteitherfromtheIDE,fromtheNUnitGUIorfromthecommandline
Forspecificdetailson.NETclientdriverconfigurationwithVisualStudio,seetheappendix
.NETclientdriverconfiguration.

UsingtheRubyClientDriver
IfyoudonotalreadyhaveRubyGems,installitfromRubyForge
Run geminstallseleniumclient
Atthetopofyourtestscript,add require"selenium/client"
WriteyourtestscriptusinganyRubytestharness(egTest::Unit,Mini::Testor
RSpec).
RunSeleniumRCserverfromtheconsole.
ExecuteyourtestinthesamewayyouwouldrunanyotherRubyscript.
FordetailsonRubyclientdriverconfiguration,seetheSeleniumClientdocumentation

FromSelenesetoaProgram
TheprimarytaskforusingSeleniumRCistoconvertyourSeleneseintoaprogramming
language.Inthissection,weprovideseveraldifferentlanguagespecificexamples.

SampleTestScript
LetsstartwithanexampleSelenesetestscript.Imaginerecordingthefollowingtestwith
SeleniumIDE.
open

type

selenium
rc

clickAndWait

btnG

assertTextPresent Results*forseleniumrc

Note:ThisexamplewouldworkwiththeGooglesearchpagehttp://www.google.com

SeleneseasProgrammingCode
Hereisthetestscriptexported(viaSeleniumIDE)toeachofthesupportedprogramming
languages.Ifyouhaveatleastbasicknowledgeofanobjectorientedprogramming
language,youwillunderstandhowSeleniumrunsSelenesecommandsbyreadingoneof
theseexamples.Toseeanexampleinaspecificlanguage,selectoneofthesebuttons.

Inthenextsectionwellexplainhowtobuildatestprogramusingthegeneratedcode.

ProgrammingYourTest
Nowwellillustratehowtoprogramyourowntestsusingexamplesineachofthesupported
programminglanguages.Thereareessentiallytwotasks:
GenerateyourscriptintoaprogramminglanguagefromSeleniumIDE,optionally
modifyingtheresult.
Writeaverysimplemainprogramthatexecutesthegeneratedcode.
Optionally,youcanadoptatestengineplatformlikeJUnitorTestNGforJava,orNUnitfor
.NETifyouareusingoneofthoselanguages.

http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

3/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation
Here,weshowlanguagespecificexamples.ThelanguagespecificAPIstendtodifferfromone
toanother,soyoullfindaseparateexplanationforeach.
Java
C#
Python
Ruby
Perl,PHP

Java
ForJava,peopleuseeitherJUnitorTestNGasthetestengine.Somedevelopment
environmentslikeEclipsehavedirectsupportfortheseviaplugins.Thismakesiteven
easier.TeachingJUnitorTestNGisbeyondthescopeofthisdocumenthowevermaterials
maybefoundonlineandtherearepublicationsavailable.Ifyouarealreadyajavashop
chancesareyourdeveloperswillalreadyhavesomeexperiencewithoneofthesetest
frameworks.
YouwillprobablywanttorenamethetestclassfromNewTesttosomethingofyourown
choosing.Also,youwillneedtochangethebrowseropenparametersinthestatement:
selenium=newDefaultSelenium("localhost",4444,"*iehta","http://www.google.com/");

TheSeleniumIDEgeneratedcodewilllooklikethis.Thisexamplehascommentsadded
manuallyforadditionalclarity.

C#
The.NETClientDriverworkswithMicrosoft.NET.Itcanbeusedwithany.NETtesting
frameworklikeNUnitortheVisualStudio2005TeamSystem.
SeleniumIDEassumesyouwilluseNUnitasyourtestingframework.Youcanseethisin
thegeneratedcodebelow.ItincludestheusingstatementforNUnitalongwith
correspondingNUnitattributesidentifyingtheroleforeachmemberfunctionofthetest
class.
YouwillprobablyhavetorenamethetestclassfromNewTesttosomethingofyourown
choosing.Also,youwillneedtochangethebrowseropenparametersinthestatement:
selenium=newDefaultSelenium("localhost",4444,"*iehta","http://www.google.com/");

Thegeneratedcodewilllooksimilartothis.

YoucanallowNUnittomanagetheexecutionofyourtests.Oralternatively,youcanwrite
asimplemain()programthatinstantiatesthetestobjectandrunseachofthethree
methods,SetupTest(),TheNewTest(),andTeardownTest()inturn.

Python
PyunitisthetestframeworktouseforPython.TolearnPyunitrefertoitsofficial
documentation<http://docs.python.org/library/unittest.html>_.
Thebasicteststructureis:

Ruby
Old(pre2.0)versionsofSeleniumIDEgenerateRubycodethatrequirestheoldSelenium
gem.Therefore,itisadvisabletoupdateanyRubyscriptsgeneratedbytheIDEasfollows:
1.Online1,change require"selenium"to require"selenium/client"
2.Online11,change Selenium::SeleniumDriver.newto Selenium::Client::Driver.new
Youprobablyalsowanttochangetheclassnametosomethingmoreinformativethan
Untitled,andchangethetestmethodsnametosomethingotherthantest_untitled.
HereisasimpleexamplecreatedbymodifyingtheRubycodegeneratedbySeleniumIDE,
asdescribedabove.

Perl,PHP
ThemembersofthedocumentationteamhavenotusedSeleniumRCwithPerlorPHP.If
youareusingSeleniumRCwitheitherofthesetwolanguagespleasecontactthe
DocumentationTeam(seethechapteroncontributing).Wewouldlovetoincludesome
examplesfromyouandyourexperiences,tosupportPerlandPHPusers.

LearningtheAPI
http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

4/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation
TheSeleniumRCAPIusesnamingconventionsthat,assumingyouunderstandSelenese,much
oftheinterfacewillbeselfexplanatory.Here,however,weexplainthemostcriticaland
possiblylessobviousaspects.

StartingtheBrowser

Eachoftheseexamplesopensthebrowserandrepresentsthatbrowserbyassigninga
browserinstancetoaprogramvariable.Thisprogramvariableisthenusedtocall
methodsfromthebrowser.ThesemethodsexecutetheSeleniumcommands,i.e.likeopen
ortypeortheverifycommands.
Theparametersrequiredwhencreatingthebrowserinstanceare:
host
SpecifiestheIPaddressofthecomputerwheretheserverislocated.Usually,thisisthe
samemachineaswheretheclientisrunning,sointhiscaselocalhostispassed.Insome
clientsthisisanoptionalparameter.
port
SpecifiestheTCP/IPsocketwheretheserverislisteningwaitingfortheclienttoestablish
aconnection.Thisalsoisoptionalinsomeclientdrivers.
browser
Thebrowserinwhichyouwanttorunthetests.Thisisarequiredparameter.
url
Thebaseurloftheapplicationundertest.Thisisrequiredbyalltheclientlibsandis
integralinformationforstartingupthebrowserproxyAUTcommunication.
Notethatsomeoftheclientlibrariesrequirethebrowsertobestartedexplicitlybycalling
itsstart()method.

RunningCommands
Onceyouhavethebrowserinitializedandassignedtoavariable(generallynamed
selenium)youcanmakeitrunSelenesecommandsbycallingtherespectivemethods
fromthebrowservariable.Forexample,tocallthetypemethodoftheseleniumobject:
selenium.type(fieldid,stringtotype)
Inthebackgroundthebrowserwillactuallyperformatypeoperation,essentiallyidentical
toausertypinginputintothebrowser,byusingthelocatorandthestringyouspecified
duringthemethodcall.

ReportingResults
SeleniumRCdoesnothaveitsownmechanismforreportingresults.Rather,itallowsyouto
buildyourreportingcustomizedtoyourneedsusingfeaturesofyourchosenprogramming
language.Thatsgreat,butwhatifyousimplywantsomethingquickthatsalreadydonefor
you?Oftenanexistinglibraryortestframeworkcanmeetyourneedsfasterthandeveloping
yourowntestreportingcode.

TestFrameworkReportingTools
Testframeworksareavailableformanyprogramminglanguages.These,alongwiththeir
primaryfunctionofprovidingaflexibletestengineforexecutingyourtests,includelibrary
codeforreportingresults.Forexample,Javahastwocommonlyusedtestframeworks,
JUnitandTestNG..NETalsohasitsown,NUnit.
Wewontteachtheframeworksthemselvesherethatsbeyondthescopeofthisuser
guide.WewillsimplyintroducetheframeworkfeaturesthatrelatetoSeleniumalongwith
sometechniquesyoucanapply.Therearegoodbooksavailableonthesetestframeworks
howeveralongwithinformationontheinternet.

TestReportLibraries
Alsoavailablearethirdpartylibrariesspecificallycreatedforreportingtestresultsinyour
chosenprogramminglanguage.TheseoftensupportavarietyofformatssuchasHTMLor
PDF.

WhatsTheBestApproach?
Mostpeoplenewtothetestingframeworkswillbeginwiththeframeworksbuiltin
reportingfeatures.Fromtheremostwillexamineanyavailablelibrariesasthatslesstime
consumingthandevelopingyourown.AsyoubegintouseSeleniumnodoubtyouwillstart
puttinginyourownprintstatementsforreportingprogress.Thatmaygraduallyleadto
youdevelopingyourownreporting,possiblyinparalleltousingalibraryortestframework.
Regardless,aftertheinitial,butshort,learningcurveyouwillnaturallydevelopwhatworks
bestforyourownsituation.

TestReportingExamples
Toillustrate,welldirectyoutosomespecifictoolsinsomeoftheotherlanguages
supportedbySelenium.Theoneslistedherearecommonlyusedandhavebeenused
extensively(andthereforerecommended)bytheauthorsofthisguide.
TestReportsinJava

http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

5/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation
IfSeleniumTestcasesaredevelopedusingJUnitthenJUnitReportcanbeusedto
generatetestreports.RefertoJUnitReportforspecifics.
IfSeleniumTestcasesaredevelopedusingTestNGthennoexternaltaskis
requiredtogeneratetestreports.TheTestNGframeworkgeneratesanHTML
reportwhichlistdetailsoftests.SeeTestNGReportformore.
ReportNGisaHTMLreportingpluginfortheTestNGframework.Itisintendedasa
replacementforthedefaultTestNGHTMLreport.ReportNGprovidesasimple,
colourcodedviewofthetestresults.SeeReportNGformore.
Also,foraverynicesummaryreporttryusingTestNGxslt.ATestNGxsltReport
lookslikethis.

SeeTestNGxsltformore.
LoggingtheSeleneseCommands
LoggingSeleniumcanbeusedtogenerateareportofalltheSelenesecommands
inyourtestalongwiththesuccessorfailureofeach.LoggingSeleniumextends
theJavaclientdrivertoaddthisSeleneseloggingability.PleaserefertoLogging
Selenium.
TestReportsforPython
WhenusingPythonClientDriverthenHTMLTestRunnercanbeusedtogeneratea
TestReport.SeeHTMLTestRunner.
TestReportsforRuby
IfRSpecframeworkisusedforwritingSeleniumTestCasesinRubythenitsHTML
reportcanbeusedtogenerateatestreport.RefertoRSpecReportformore.
Note
Ifyouareinterestedinalanguageindependentlogofwhatsgoingon,takealookat
SeleniumServerLogging

AddingSomeSpicetoYourTests
NowwellgettothewholereasonforusingSeleniumRC,addingprogramminglogictoyour
tests.Itsthesameasforanyprogram.Programflowiscontrolledusingconditionstatements
anditeration.InadditionyoucanreportprogressinformationusingI/O.Inthissectionwell
showsomeexamplesofhowprogramminglanguageconstructscanbecombinedwith
Seleniumtosolvecommontestingproblems.
Youwillfindasyoutransitionfromthesimpletestsoftheexistenceofpageelementstotests
ofdynamicfunctionalityinvolvingmultiplewebpagesandvaryingdatathatyouwillrequire
programminglogicforverifyingexpectedresults.Basically,theSeleniumIDEdoesnotsupport
iterationandstandardconditionstatements.Youcandosomeconditionsbyembedding
javascriptinSeleneseparameters,howeveriterationisimpossible,andmostconditionswillbe
mucheasierinaprogramminglanguage.Inaddition,youmayneedexceptionhandlingfor
errorrecovery.Forthesereasonsandothers,wehavewrittenthissectiontoillustratetheuse
ofcommonprogrammingtechniquestogiveyougreaterverificationpowerinyourautomated
testing.
TheexamplesinthissectionarewritteninC#andJava,althoughthecodeissimpleandcan
beeasilyadaptedtotheothersupportedlanguages.Ifyouhavesomebasicknowledgeofan
objectorientedprogramminglanguageyoushouldnthavedifficultyunderstandingthissection.

Iteration
Iterationisoneofthemostcommonthingspeopleneedtodointheirtests.Forexample,
youmaywanttotoexecuteasearchmultipletimes.Or,perhapsforverifyingyourtest
resultsyouneedtoprocessaresultsetreturnedfromadatabase.
UsingthesameGooglesearchexampleweusedearlier,letschecktheSeleniumsearch
results.ThistestcouldusetheSelenese:
open

type

seleniumrc

clickAndWait

btnG

http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

6/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation
assertTextPresent Results*forseleniumrc

type

seleniumide

clickAndWait

btnG

assertTextPresent Results*forseleniumide

type

selenium
grid

clickAndWait

btnG

assertTextPresent Results*forseleniumgrid

Thecodehasbeenrepeatedtorunthesamesteps3times.Butmultiplecopiesofthesame
codeisnotgoodprogrampracticebecauseitsmoreworktomaintain.Byusinga
programminglanguage,wecaniterateoverthesearchresultsforamoreflexibleand
maintainablesolution.
InC#:
//CollectionofStringvalues.
String[]arr={"ide","rc","grid"};
//ExecuteloopforeachStringinarray'arr'.
foreach(Stringsinarr){
sel.open("/");
sel.type("q","selenium"+s);
sel.click("btnG");
sel.waitForPageToLoad("30000");
assertTrue("Expectedtext:"+s+"ismissingonpage."
,sel.isTextPresent("Results*forselenium"+s));
}

ConditionStatements
Toillustrateusingconditionsintestswellstartwithanexample.Acommonproblem
encounteredwhilerunningSeleniumtestsoccurswhenanexpectedelementisnotavailable
onpage.Forexample,whenrunningthefollowingline:

Ifelementqisnotonthepagethenanexceptionisthrown:

Thiscancauseyourtesttoabort.Forsometeststhatswhatyouwant.Butoftenthatisnot
desirableasyourtestscripthasmanyothersubsequentteststoperform.
Abetterapproachistofirstvalidatewhethertheelementisreallypresentandthentake
alternativeswhenititisnot.LetslookatthisusingJava.

TheadvantageofthisapproachistocontinuewithtestexecutionevenifsomeUIelements
arenotavailableonpage.

ExecutingJavaScriptfromYourTest
JavaScriptcomesveryhandyinexercisinganapplicationwhichisnotdirectlysupportedby
selenium.ThegetEvalmethodofseleniumAPIcanbeusedtoexecuteJavaScriptfrom
seleniumRC.
Consideranapplicationhavingcheckboxeswithnostaticidentifiers.Inthiscaseonecould
evaluateJavaScriptfromseleniumRCtogetidsofallcheckboxesandthenexercisethem.

Tocountnumberofimagesonapage:

RemembertousewindowobjectincaseofDOMexpressionsasbydefaultseleniumwindow
isreferredto,notthetestwindow.

ServerOptions
Whentheserverislaunched,commandlineoptionscanbeusedtochangethedefaultserver
behaviour.
Recall,theserverisstartedbyrunningthefollowing.
$javajarseleniumserverstandalone<versionnumber>.jar

Toseethelistofoptions,runtheserverwiththe hoption.
$javajarseleniumserverstandalone<versionnumber>.jarh

Youllseealistofalltheoptionsyoucanusewiththeserverandabriefdescriptionofeach.
Theprovideddescriptionswillnotalwaysbeenough,soweveprovidedexplanationsforsome
ofthemoreimportantoptions.

http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

7/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation

ProxyConfiguration
IfyourAUTisbehindanHTTPproxywhichrequiresauthenticationthenyoushould
configurehttp.proxyHost,http.proxyPort,http.proxyUserandhttp.proxyPasswordusingthe
followingcommand.
$javajarseleniumserverstandalone<versionnumber>.jarDhttp.proxyHost=proxy.comDhttp.proxyPort=8080

MultiWindowMode
IfyouareusingSelenium1.0youcanprobablyskipthissection,sincemultiwindowmode
isthedefaultbehavior.However,priortoversion1.0,Seleniumbydefaultranthe
applicationundertestinasubframeasshownhere.

Someapplicationsdidntruncorrectlyinasubframe,andneededtobeloadedintothetop
frameofthewindow.ThemultiwindowmodeoptionallowedtheAUTtoruninaseparate
windowratherthaninthedefaultframewhereitcouldthenhavethetopframeitrequired.

http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

8/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation

ForolderversionsofSeleniumyoumustspecifymultiwindowmodeexplicitlywiththe
followingoption:
multiwindow

AsofSeleniumRC1.0,ifyouwanttorunyourtestwithinasingleframe(i.e.usingthe
standardforearlierSeleniumversions)youcanstatethistotheSeleniumServerusingthe
option
singlewindow

SpecifyingtheFirefoxProfile
Firefoxwillnotruntwoinstancessimultaneouslyunlessyouspecifyaseparateprofilefor
eachinstance.SeleniumRC1.0andlaterrunsinaseparateprofileautomatically,soifyou
areusingSelenium1.0,youcanprobablyskipthissection.However,ifyoureusingan
olderversionofSeleniumorifyouneedtouseaspecificprofileforyourtests(suchas
addinganhttpscertificateorhavingsomeaddonsinstalled),youwillneedtoexplicitly
specifytheprofile.
First,tocreateaseparateFirefoxprofile,followthisprocedure.OpentheWindowsStart
menu,selectRun,thentypeandenteroneofthefollowing:
firefox.exeprofilemanager
firefox.exeP

Createthenewprofileusingthedialog.ThenwhenyourunSeleniumServer,tellittouse
thisnewFirefoxprofilewiththeservercommandlineoptionfirefoxProfileTemplateand
specifythepathtotheprofileusingitsfilenameanddirectorypath.
firefoxProfileTemplate"pathtotheprofile"

Warning
Besuretoputyourprofileinanewfolderseparatefromthedefault!!!TheFirefoxprofile
managertoolwilldeleteallfilesinafolderifyoudeleteaprofile,regardlessofwhether
theyareprofilefilesornot.
MoreinformationaboutFirefoxprofilescanbefoundinMozillasKnowledgeBase

RunSeleneseDirectlyWithintheServerUsinghtmlSuite
YoucanrunSelenesehtmlfilesdirectlywithintheSeleniumServerbypassingthehtmlfile
totheserverscommandline.Forinstance:
javajarseleniumserverstandalone<versionnumber>.jarhtmlSuite"*firefox"
"http://www.google.com""c:\absolute\path\to\my\HTMLSuite.html"
"c:\absolute\path\to\my\results.html"

ThiswillautomaticallylaunchyourHTMLsuite,runallthetestsandsaveaniceHTML
reportwiththeresults.

http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

9/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation
Note
Whenusingthisoption,theserverwillstartthetestsandwaitforaspecifiednumberof
secondsforthetesttocompleteifthetestdoesntcompletewithinthatamountoftime,
thecommandwillexitwithanonzeroexitcodeandnoresultsfilewillbegenerated.
Thiscommandlineisverylongsobecarefulwhenyoutypeit.Notethisrequiresyouto
passinanHTMLSelenesesuite,notasingletest.AlsobeawarethehtmlSuiteoptionis
incompatiblewith interactiveYoucannotrunbothatthesametime.

SeleniumServerLogging
ServerSideLogs
Whenlaunchingseleniumserverthelogoptioncanbeusedtorecordvaluable
debugginginformationreportedbytheSeleniumServertoatextfile.
javajarseleniumserverstandalone<versionnumber>.jarlogselenium.log

Thislogfileismoreverbosethanthestandardconsolelogs(itincludesDEBUGlevel
loggingmessages).Thelogfilealsoincludestheloggername,andtheIDnumberofthe
threadthatloggedthemessage.Forexample:
20:44:25DEBUG[12]org.openqa.selenium.server.SeleniumDriverResourceHandler
Browser465828/:topframe1postedSTARTNEW

Themessageformatis
TIMESTAMP(HH:mm:ss)LEVEL[THREAD]LOGGERMESSAGE

Thismessagemaybemultiline.
BrowserSideLogs
JavaScriptonthebrowserside(SeleniumCore)alsologsimportantmessagesinmany
cases,thesecanbemoreusefultotheenduserthantheregularSeleniumServerlogs.
Toaccessbrowsersidelogs,passthebrowserSideLogargumenttotheSelenium
Server.
javajarseleniumserverstandalone<versionnumber>.jarbrowserSideLog

browserSideLogmustbecombinedwiththelogargument,tologbrowserSideLogs(as
wellasallotherDEBUGlevelloggingmessages)toafile.

SpecifyingthePathtoaSpecificBrowser
YoucanspecifytoSeleniumRCapathtoaspecificbrowser.Thisisusefulifyouhave
differentversionsofthesamebrowserandyouwishtouseaspecificone.Also,thisisusedto
allowyourteststorunagainstabrowsernotdirectlysupportedbySeleniumRC.When
specifyingtherunmode,usethe*customspecifierfollowedbythefullpathtothebrowsers
executable:
*custom<pathtobrowser>

SeleniumRCArchitecture
Note
ThistopictriestoexplainthetechnicalimplementationbehindSeleniumRC.Itsnot
fundamentalforaSeleniumusertoknowthis,butcouldbeusefulforunderstandingsomeof
theproblemsyoumightfindinthefuture.
TounderstandindetailhowSeleniumRCServerworksandwhyitusesproxyinjectionand
heightenedprivilegemodesyoumustfirstunderstandthesameoriginpolicy.

TheSameOriginPolicy
ThemainrestrictionthatSeleniumfacesistheSameOriginPolicy.Thissecurityrestriction
isappliedbyeverybrowserinthemarketanditsobjectiveistoensurethatasitescontent
willneverbeaccessiblebyascriptfromanothersite.TheSameOriginPolicydictatesthat
anycodeloadedwithinthebrowsercanonlyoperatewithinthatwebsitesdomain.Itcannot
performfunctionsonanotherwebsite.Soforexample,ifthebrowserloadsJavaScriptcode
whenitloadswww.mysite.com,itcannotrunthatloadedcodeagainstwww.mysite2.com
evenifthatsanotherofyoursites.Ifthiswerepossible,ascriptplacedonanywebsiteyou
openwouldbeabletoreadinformationonyourbankaccountifyouhadtheaccountpage
openedonothertab.ThisiscalledXSS(CrosssiteScripting).
Toworkwithinthispolicy,SeleniumCore(anditsJavaScriptcommandsthatmakeallthe
magichappen)mustbeplacedinthesameoriginastheApplicationUnderTest(same
URL).
Historically,SeleniumCorewaslimitedbythisproblemsinceitwasimplementedin
JavaScript.SeleniumRCisnot,however,restrictedbytheSameOriginPolicy.Itsuseof
theSeleniumServerasaproxyavoidsthisproblem.It,essentially,tellsthebrowserthat
thebrowserisworkingonasinglespoofedwebsitethattheServerprovides.
Note

http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

10/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation
YoucanfindadditionalinformationaboutthistopiconWikipediapagesaboutSameOrigin
PolicyandXSS.

ProxyInjection
ThefirstmethodSeleniumusedtoavoidtheTheSameOriginPolicywasProxyInjection.In
ProxyInjectionMode,theSeleniumServeractsasaclientconfigured[1]HTTPproxy[2],
thatsitsbetweenthebrowserandtheApplicationUnderTest.ItthenmaskstheAUTunder
afictionalURL(embeddingSeleniumCoreandthesetoftestsanddeliveringthemasif
theywerecomingfromthesameorigin).
[1] Theproxyisathirdpersoninthemiddlethatpassestheballbetweenthetwoparts.It
actsasawebserverthatdeliverstheAUTtothebrowser.Beingaproxygives
SeleniumServerthecapabilityoflyingabouttheAUTsrealURL.
[2] Thebrowserislaunchedwithaconfigurationprofilethathassetlocalhost:4444asthe
HTTPproxy,thisiswhyanyHTTPrequestthatthebrowserdoeswillpassthrough
Seleniumserverandtheresponsewillpassthroughitandnotfromtherealserver.
Hereisanarchitecturaldiagram.

Asatestsuitestartsinyourfavoritelanguage,thefollowinghappens:
1. Theclient/driverestablishesaconnectionwiththeseleniumRCserver.
2. SeleniumRCserverlaunchesabrowser(orreusesanoldone)withaURLthatinjects
SeleniumCoresJavaScriptintothebrowserloadedwebpage.
3. TheclientdriverpassesaSelenesecommandtotheserver.
4. TheServerinterpretsthecommandandthentriggersthecorrespondingJavaScript
executiontoexecutethatcommandwithinthebrowser.SeleniumCoreinstructsthe
browsertoactonthatfirstinstruction,typicallyopeningapageoftheAUT.
5. Thebrowserreceivestheopenrequestandasksforthewebsitescontentfromthe
SeleniumRCserver(setastheHTTPproxyforthebrowsertouse).
6. SeleniumRCservercommunicateswiththeWebserveraskingforthepageandonce
itreceivesit,itsendsthepagetothebrowsermaskingtheorigintolooklikethe
pagecomesfromthesameserverasSeleniumCore(thisallowsSeleniumCoreto
complywiththeSameOriginPolicy).
7. Thebrowserreceivesthewebpageandrendersitintheframe/windowreservedfor
it.

http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

11/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation

HeightenedPrivilegesBrowsers
ThisworkflowinthismethodisverysimilartoProxyInjectionbutthemaindifferenceis
thatthebrowsersarelaunchedinaspecialmodecalledHeightenedPrivileges,whichallows
websitestodothingsthatarenotcommonlypermitted(asdoingXSS,orfillingfileupload
inputsandprettyusefulstuffforSelenium).Byusingthesebrowsermodes,SeleniumCore
isabletodirectlyopentheAUTandread/interactwithitscontentwithouthavingtopass
thewholeAUTthroughtheSeleniumRCserver.
Hereisthearchitecturaldiagram.

Asatestsuitestartsinyourfavoritelanguage,thefollowinghappens:
1. Theclient/driverestablishesaconnectionwiththeseleniumRCserver.
2. SeleniumRCserverlaunchesabrowser(orreusesanoldone)withaURLthatwill
loadSeleniumCoreinthewebpage.
3. SeleniumCoregetsthefirstinstructionfromtheclient/driver(viaanotherHTTP
requestmadetotheSeleniumRCServer).
4. SeleniumCoreactsonthatfirstinstruction,typicallyopeningapageoftheAUT.
5. ThebrowserreceivestheopenrequestandaskstheWebServerforthepage.Once
thebrowserreceivesthewebpage,rendersitintheframe/windowreservedforit.

HandlingHTTPSandSecurityPopups
ManyapplicationsswitchfromusingHTTPtoHTTPSwhentheyneedtosendencrypted
informationsuchaspasswordsorcreditcardinformation.Thisiscommonwithmanyof
todayswebapplications.SeleniumRCsupportsthis.
ToensuretheHTTPSsiteisgenuine,thebrowserwillneedasecuritycertificate.Otherwise,
whenthebrowseraccessestheAUTusingHTTPS,itwillassumethatapplicationisnot
trusted.Whenthisoccursthebrowserdisplayssecuritypopups,andthesepopupscannotbe
closedusingSeleniumRC.
WhendealingwithHTTPSinaSeleniumRCtest,youmustusearunmodethatsupportsthis
andhandlesthesecuritycertificateforyou.Youspecifytherunmodewhenyourtestprogram
initializesSelenium.
InSeleniumRC1.0beta2andlateruse*firefoxor*iexplorefortherunmode.Inearlier

http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

12/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation
versions,includingSeleniumRC1.0beta1,use*chromeor*iehta,fortherunmode.Using
theserunmodes,youwillnotneedtoinstallanyspecialsecuritycertificatesSeleniumRCwill
handleitforyou.
Inversion1.0therunmodes*firefoxor*iexplorearerecommended.However,thereare
additionalrunmodesof*iexploreproxyand*firefoxproxy.Theseareprovidedforbackwards
compatibilityonly,andshouldnotbeusedunlessrequiredbylegacytestprograms.Theiruse
willpresentlimitationswithsecuritycertificatehandlingandwiththerunningofmultiple
windowsifyourapplicationopensadditionalbrowserwindows.
InearlierversionsofSeleniumRC,*chromeor*iehtaweretherunmodesthatsupported
HTTPSandthehandlingofsecuritypopups.Thesewereconsideredexperimentalmodes
althoughtheybecamequitestableandmanypeopleusedthem.IfyouareusingSelenium1.0
youdonotneed,andshouldnotuse,theseolderrunmodes.

SecurityCertificatesExplained
Normally,yourbrowserwilltrusttheapplicationyouaretestingbyinstallingasecurity
certificatewhichyoualreadyown.YoucancheckthisinyourbrowsersoptionsorInternet
properties(ifyoudontknowyourAUTssecuritycertificateaskyoursystem
administrator).WhenSeleniumloadsyourbrowseritinjectscodetointerceptmessages
betweenthebrowserandtheserver.Thebrowsernowthinksuntrustedsoftwareistrying
tolooklikeyourapplication.Itrespondsbyalertingyouwithpopupmessages.
Togetaroundthis,SeleniumRC,(againwhenusingarunmodethatsupportthis)will
installitsownsecuritycertificate,temporarily,toyourclientmachineinaplacewherethe
browsercanaccessit.Thistricksthebrowserintothinkingitsaccessingasitedifferent
fromyourAUTandeffectivelysuppressesthepopups.
AnothermethodusedwithearlierversionsofSeleniumwastoinstalltheCybervillians
securitycertificateprovidedwithyourSeleniuminstallation.Mostusersshouldnolonger
needtodothishoweverifyouarerunningSeleniumRCinproxyinjectionmode,youmay
needtoexplicitlyinstallthissecuritycertificate.

SupportingAdditionalBrowsersandBrowserConfigurations
TheSeleniumAPIsupportsrunningagainstmultiplebrowsersinadditiontoInternetExplorer
andMozillaFirefox.SeetheSeleniumHQ.orgwebsiteforsupportedbrowsers.Inaddition,
whenabrowserisnotdirectlysupported,youmaystillrunyourSeleniumtestsagainsta
browserofyourchoosingbyusingthe*customrunmode(i.e.inplaceof*firefoxor
*iexplore)whenyourtestapplicationstartsthebrowser.Withthis,youpassinthepathtothe
browsersexecutablewithintheAPIcall.ThiscanalsobedonefromtheServerininteractive
mode.
cmd=getNewBrowserSession&1=*customc:\ProgramFiles\MozillaFirefox\MyBrowser.exe&2=http://www.google.com

RunningTestswithDifferentBrowserConfigurations
NormallySeleniumRCautomaticallyconfiguresthebrowser,butifyoulaunchthebrowser
usingthe*customrunmode,youcanforceSeleniumRCtolaunchthebrowserasis,
withoutusinganautomaticconfiguration.
Forexample,youcanlaunchFirefoxwithacustomconfigurationlikethis:
cmd=getNewBrowserSession&1=*customc:\ProgramFiles\MozillaFirefox\firefox.exe&2=http://www.google.com

Notethatwhenlaunchingthebrowserthisway,youmustmanuallyconfigurethebrowser
stopfollowingme!
ProgrammingLanguagePreference
tousetheSeleniumServerasaproxy.Normallythisjustmeansopeningyourbrowser
preferencesandspecifyinglocalhost:4444asanHTTPproxy,butinstructionsforthiscan
differradicallyfrombrowsertobrowser.Consultyourbrowsersdocumentationfordetails.
BeawarethatMozillabrowserscanvaryinhowtheystartandstop.Onemayneedtoset
theMOZ_NO_REMOTEenvironmentvariabletomakeMozillabrowsersbehavealittlemore
predictably.Unixusersshouldavoidlaunchingthebrowserusingashellscriptits
generallybettertousethebinaryexecutable(e.g.firefoxbin)directly.

TroubleshootingCommonProblems
WhengettingstartedwithSeleniumRCtheresafewpotentialproblemsthatarecommonly
encountered.Wepresentthemalongwiththeirsolutionshere.

UnabletoConnecttoServer
WhenyourtestprogramcannotconnecttotheSeleniumServer,Seleniumthrowsan
exceptioninyourtestprogram.Itshoulddisplaythismessageorasimilarone:
"Unabletoconnecttoremoteserver(InnerExceptionMessage:
Noconnectioncouldbemadebecausethetargetmachineactively
refusedit)"
(using.NETandXPServicePack2)

Ifyouseeamessagelikethis,besureyoustartedtheSeleniumServer.Ifso,thenthereis
aproblemwiththeconnectivitybetweentheSeleniumClientLibraryandtheSelenium
Server.
WhenstartingwithSeleniumRC,mostpeoplebeginbyrunningtheirtestprogram(witha

http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

13/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation
SeleniumClientLibrary)andtheSeleniumServeronthesamemachine.Todothisuse
localhostasyourconnectionparameter.Werecommendbeginningthiswaysinceit
reducestheinfluenceofpotentialnetworkingproblemswhichyouregettingstarted.
AssumingyouroperatingsystemhastypicalnetworkingandTCP/IPsettingsyoushould
havelittledifficulty.Intruth,manypeoplechoosetoruntheteststhisway.
If,however,youdowanttorunSeleniumServeronaremotemachine,theconnectivity
shouldbefineassumingyouhavevalidTCP/IPconnectivitybetweenthetwomachines.
Ifyouhavedifficultyconnecting,youcanusecommonnetworkingtoolslikeping,telnet,
ifconfig(Unix)/ipconfig(Windows),etctoensureyouhaveavalidnetworkconnection.If
unfamilarwiththese,yoursystemadministratorcanassistyou.

UnabletoLoadtheBrowser
Ok,notafriendlyerrormessage,sorry,butiftheSeleniumServercannotloadthebrowser
youwilllikelyseethiserror.
(500)InternalServerError

Thiscouldbecausedby
Firefox(priortoSelenium1.0)cannotstartbecausethebrowserisalreadyopenand
youdidnotspecifyaseparateprofile.SeethesectiononFirefoxprofilesunder
ServerOptions.
Therunmodeyoureusingdoesntmatchanybrowseronyourmachine.Checkthe
parametersyoupassedtoSeleniumwhenyouprogramopensthebrowser.
Youspecifiedthepathtothebrowserexplicitly(using*customseeabove)butthe
pathisincorrect.Checktobesurethepathiscorrect.Alsochecktheusergroupto
besuretherearenoknownissueswithyourbrowserandthe*customparameters.

SeleniumCannotFindtheAUT
Ifyourtestprogramstartsthebrowsersuccessfully,butthebrowserdoesntdisplaythe
websiteyouretesting,themostlikelycauseisyourtestprogramisnotusingthecorrect
URL.
Thiscaneasilyhappen.WhenyouuseSeleniumIDEtoexportyourscript,itinsertsa
dummyURL.YoumustmanuallychangetheURLtothecorrectoneforyourapplicationto
betested.

FirefoxRefusedShutdownWhilePreparingaProfile
ThismostoftenoccurswhenyourunyourSeleniumRCtestprogramagainstFirefox,but
youalreadyhaveaFirefoxbrowsersessionrunningand,youdidntspecifyaseparate
profilewhenyoustartedtheSeleniumServer.Theerrorfromthetestprogramlookslike
this:
Error:java.lang.RuntimeException:Firefoxrefusedshutdownwhile
preparingaprofile

Heresthecompleteerrormessagefromtheserver:
16:20:03.919INFOPreparingFirefoxprofile...
16:20:27.822WARNGET/seleniumserver/driver/?cmd=getNewBrowserSession&1=*fir
efox&2=http%3a%2f%2fsagewebapp1.qa.idc.comHTTP/1.1
java.lang.RuntimeException:Firefoxrefusedshutdownwhilepreparingaprofile
atorg.openqa.selenium.server.browserlaunchers.FirefoxCustomProfileLaunc
her.waitForFullProfileToBeCreated(FirefoxCustomProfileLauncher.java:277)
...
Causedby:org.openqa.selenium.server.browserlaunchers.FirefoxCustomProfileLaunc
her$FileLockRemainedException:Lockfilestillpresent!C:\DOCUME~1\jsvec\LOCALS
~1\Temp\customProfileDir203138\parent.lock

Toresolvethis,seethesectiononSpecifyingaSeparateFirefoxProfile

VersioningProblems
MakesureyourversionofSeleniumsupportstheversionofyourbrowser.Forexample,
SeleniumRC0.92doesnotsupportFirefox3.Attimesyoumaybelucky(Iwas).Butdont
forgettocheckwhichbrowserversionsaresupportedbytheversionofSeleniumyouare
using.Whenindoubt,usethelatestreleaseversionofSeleniumwiththemostwidelyused
versionofyourbrowser.

Errormessage:(Unsupportedmajor.minorversion49.0)whilestartingserver
ThiserrorsaysyourenotusingacorrectversionofJava.TheSeleniumServerrequires
Java1.5orhigher.
Tocheckdoublecheckyourjavaversion,runthisfromthecommandline.
javaversion

YoushouldseeamessageshowingtheJavaversion.
javaversion"1.5.0_07"
Java(TM)2RuntimeEnvironment,StandardEdition(build1.5.0_07b03)
JavaHotSpot(TM)ClientVM(build1.5.0_07b03,mixedmode)

http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

14/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation
Ifyouseealowerversionnumber,youmayneedtoupdatetheJRE,oryoumaysimply
needtoaddittoyourPATHenvironmentvariable.

404errorwhenrunningthegetNewBrowserSessioncommand
Ifyouregettinga404errorwhileattemptingtoopenapageon
http://www.google.com/seleniumserver/,thenitmustbebecausetheSeleniumServer
wasnotcorrectlyconfiguredasaproxy.Theseleniumserverdirectorydoesntexiston
google.comitonlyappearstoexistwhentheproxyisproperlyconfigured.Proxy
Configurationhighlydependsonhowthebrowserislaunchedwith*firefox,*iexplore,
*opera,or*custom.
*iexplore:Ifthebrowserislaunchedusing*iexplore,you
couldbehavingaproblemwithInternetExplorersproxy
settings.SeleniumServerattemptsToconfiguretheglobal
proxysettingsintheInternetOptionsControlPanel.Youmust
makesurethatthosearecorrectlyconfiguredwhenSelenium
Serverlaunchesthebrowser.TrylookingatyourInternet
Optionscontrolpanel.ClickontheConnectionstabandclick
onLANSettings.
Ifyouneedtouseaproxytoaccesstheapplicationyou
wanttotest,youllneedtostartSeleniumServerwith
Dhttp.proxyHostseetheProxyConfigurationfor
moredetails.
Youmayalsotryconfiguringyourproxymanuallyand
thenlaunchingthebrowserwith*custom,orwith*iehta
browserlauncher.
*custom:Whenusing*customyoumustconfiguretheproxy
correctly(manually),
otherwiseyoullgeta404error.Doublecheckthatyouveconfigured
yourproxysettingscorrectly.Tocheckwhetheryouveconfiguredthe
proxycorrectlyistoattempttointentionallyconfigurethebrowser
incorrectly.Tryconfiguringthebrowsertousethewrongproxyserver
hostname,orthewrongport.Ifyouhadsuccessfullyconfiguredthe
browsersproxysettingsincorrectly,thenthebrowserwillbeunableto
connecttotheInternet,whichisonewaytomakesurethatoneis
adjustingtherelevantsettings.
Forotherbrowsers(*firefox,*opera)weautomaticallyhardcodethe
proxyforyou,andsotherearenoknownissueswiththisfunctionality.If
youreencountering404errorsandhavefollowedthisuserguidecarefully
postyourresultstousergroupforsomehelpfromtheusercommunity.

PermissionDeniedError
Themostcommonreasonforthiserroristhatyoursessionisattemptingtoviolatethe
sameoriginpolicybycrossingdomainboundaries(e.g.,accessesapagefrom
http://domain1andthenaccessesapagefromhttp://domain2)orswitchingprotocols
(movingfromhttp://domainXtohttps://domainX).
ThiserrorcanalsooccurwhenJavaScriptattemptstofindUIobjectswhicharenotyet
available(beforethepagehascompletelyloaded),orarenolongeravailable(afterthe
pagehasstartedtobeunloaded).ThisismosttypicallyencounteredwithAJAXpageswhich
areworkingwithsectionsofapageorsubframesthatloadand/orreloadindependentlyof
thelargerpage.
Thiserrorcanbeintermittent.Oftenitisimpossibletoreproducetheproblemwitha
debuggerbecausethetroublestemsfromraceconditionswhicharenotreproduciblewhen
thedebuggersoverheadisaddedtothesystem.Permissionissuesarecoveredinsome
detailinthetutorial.ReadthesectionabouttheTheSameOriginPolicy,ProxyInjection
carefully.

HandlingBrowserPopupWindows
ThereareseveralkindsofPopupsthatyoucangetduringaSeleniumtest.Youmaynot
beabletoclosethesepopupsbyrunningseleniumcommandsiftheyareinitiatedbythe
browserandnotyourAUT.Youmayneedtoknowhowtomanagethese.Eachtypeof
popupneedstobeaddresseddifferently.
HTTPbasicauthenticationdialogs:Thesedialogspromptfora
username/passwordtologintothesite.Tologintoasitethatrequires
HTTPbasicauthentication,useausernameandpasswordintheURL,as
describedinRFC1738,likethis:
open(http://myusername:myuserpassword@myexample.com/blah/blah/blah).
SSLcertificatewarnings:SeleniumRCautomaticallyattemptstospoof
SSLcertificateswhenitisenabledasaproxyseemoreonthisinthe
sectiononHTTPS.Ifyourbrowserisconfiguredcorrectly,youshould
neverseeSSLcertificatewarnings,butyoumayneedtoconfigureyour
browsertotrustourdangerousCyberVillainsSSLcertificateauthority.
Again,refertotheHTTPSsectionforhowtodothis.
modalJavaScriptalert/confirmation/promptdialogs:Seleniumtriesto
concealthosedialogsfromyou(byreplacingwindow.alert,
window.confirmandwindow.prompt)sotheywontstoptheexecutionof
yourpage.Ifyoureseeinganalertpopup,itsprobablybecauseitfired
duringthepageloadprocess,whichisusuallytooearlyforustoprotect

http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

15/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation
thepage.Selenesecontainscommandsforassertingorverifyingalert
andconfirmationpopups.SeethesectionsonthesetopicsinChapter4.

OnLinux,whyisntmyFirefoxbrowsersessionclosing?
OnUnix/Linuxyoumustinvokefirefoxbindirectly,somakesurethatexecutableison
thepath.IfexecutingFirefoxthroughashellscript,whenitcomestimetokillthebrowser
SeleniumRCwillkilltheshellscript,leavingthebrowserrunning.Youcanspecifythepath
tofirefoxbindirectly,likethis.
cmd=getNewBrowserSession&1=*firefox/usr/local/firefox/firefoxbin&2=http://www.google.com

Firefox*chromedoesntworkwithcustomprofile
CheckFirefoxprofilefolder>prefs.js>user_pref(browser.startup.page,0)Comment
thislinelikethis://user_pref(browser.startup.page,0)andtryagain.

Isitoktoloadacustompopupastheparentpageisloading(i.e.,beforetheparent
pagesjavascriptwindow.onload()functionruns)?
No.Seleniumreliesoninterceptorstodeterminewindownamesastheyarebeingloaded.
TheseinterceptorsworkbestincatchingnewwindowsifthewindowsareloadedAFTERthe
onload()function.Seleniummaynotrecognizewindowsloadedbeforetheonloadfunction.

ProblemsWithVerifyCommands
IfyouexportyourtestsfromSeleniumIDE,youmayfindyourselfgettingemptyverify
stringsfromyourtests(dependingontheprogramminglanguageused).
Note:Thissectionisnotyetdeveloped.

SafariandMultiWindowMode
Note:Thissectionisnotyetdeveloped.

FirefoxonLinux
OnUnix/Linux,versionsofSeleniumbefore1.0neededtoinvokefirefoxbindirectly,soif
youareusingapreviousversion,makesurethattherealexecutableisonthepath.
OnmostLinuxdistributions,therealfirefoxbinislocatedon:
/usr/lib/firefoxx.x.x/

Wherethex.x.xistheversionnumberyoucurrentlyhave.So,toaddthatpathtothe
userspath.youwillhavetoaddthefollowingtoyour.bashrcfile:
exportPATH="$PATH:/usr/lib/firefoxx.x.x/"

Ifnecessary,youcanspecifythepathtofirefoxbindirectlyinyourtest,likethis:
"*firefox/usr/lib/firefoxx.x.x/firefoxbin"

IEandStyleAttributes
IfyouarerunningyourtestsonInternetExplorerandyoucannotlocateelementsusing
theirstyleattribute.Forexample:
//td[@style="backgroundcolor:yellow"]

ThiswouldworkperfectlyinFirefox,OperaorSafaributnotwithIE.IEinterpretsthekeys
in@styleasuppercase.So,evenifthesourcecodeisinlowercase,youshoulduse:
//td[@style="BACKGROUNDCOLOR:yellow"]

Thisisaproblemifyourtestisintendedtoworkonmultiplebrowsers,butyoucaneasily
codeyourtesttodetectthesituationandtrythealternativelocatorthatonlyworksinIE.

ErrorencounteredCannotconvertobjecttoprimitivevaluewithshutdownof
*googlechromebrowser
Toavoidthiserroryouhavetostartbrowserwithanoptionthatdisablessameoriginpolicy
checks:
selenium.start("commandLineFlags=disablewebsecurity");

ErrorencounteredinIECouldntopenappwindowisthepopupblocker
enabled?
Toavoidthiserroryouhavetoconfigurethebrowser:disablethepopupblockerAND
uncheckEnableProtectedModeoptioninTools>>Options>>Security.

WherecanIAskQuestionsthatArentAnsweredHere?
Tryourusergroup

Navigation
http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

16/17

01/07/2015

Selenium1(SeleniumRC)SeleniumDocumentation
SeleniumDocumentation
previous| next
Copyright20082012,SeleniumProject.LastupdatedonJun29,2015.

SeleniumProjects

Documentation

Support

AboutSelenium

SeleniumIDE
SeleniumRemoteControl
SeleniumWebDriver
SeleniumGrid

Onlineversion
Wiki
SeleniumAPI

UserGroup
BugTracker
CommercialSupport
IRC

News/Blogs
Events
WhomadeSelenium
Roadmap
GettingInvolved

http://www.seleniumhq.org/docs/05_selenium_rc.jsp#java

17/17

Anda mungkin juga menyukai