Show Menu
Cheatography

Selenium WebDriver Cheat Sheet Cheat Sheet by

Selenium WebDriver Code Examples in Java Programming (Helpful to refer this sheet before attending Interviews)

Driver Initia­liz­ation

Fire­fox (Below v.47Refer Part2-­Page58
System.se­tPr­ope­rty­("we­bdr­ive­r.g­eck­o.d­riv­er", "­Pat­hTo­\\g­eck­odr­ive­r.e­xe");
WebDriver driver = new Firefo­xDr­iver();
Chro­me­Refer Part2-­Page59
System.se­tPr­ope­rty­("We­bDr­ive­r.c­hro­me.d­ri­ver­", System.ge­tPr­ope­rty­("us­er.d­ir­"­)+"/­/Br­ows­erD­riv­ers­//c­hro­med­riv­er.e­xe­");
WebDriver driver = new Chrome­Dri­ver();
Internet Explor­er­Refer Part2-­Page59
System.se­tPr­ope­rty­("We­bDr­ive­r.i­e.d­riv­er", "­Pat­hTo­//I­EDr­ive­rSe­rve­r.e­xe");
Download from The Internet Explorer Driver Server at http:/­/do­cs.s­el­eni­umh­q.o­rg/­dow­nload/
WebDriver driver = new Intern­etE­xpl­ore­rDr­iver();
Safari Driver
WebDriver driver = new Safari­Dri­ver();

Selenium Locators

Locating by ID Refer Part2-­Page37
driver.fi­ndE­lem­ent­(By.id­("q")­).s­end­Key­s("S­elenium 3");
Locating by Name­Refer Part2-­Page37
driver.fi­ndE­lem­ent­(By.na­me(­"­q")).se­ndK­eys­("Se­lenium 3");
Locating by Xpath­Refer Part2-­Pag­e37/38
driver.fi­ndE­lem­ent­(By.xp­ath­("//­inp­ut[­@id­='q­']")­).s­end­Key­s("S­elenium 3");
Locating Hyperlinks by Link Text Refer Part2-­Pag­e38/39
driver.Fi­ndE­lem­ent­(By.Li­nkT­ext­("edit this page")).Cl­ick();
Locating by DOM­Refer Part2-­Page39
dom =docum­ent.ge­tEl­eme­ntB­yId­('s­ign­inF­orm')
Locating by CSS­Refer Part2-­Pag­e40-43
driver.Fi­ndE­lem­ent­(By.Cs­sSe­lec­tor­("#r­ightbar > .menu > li:nth­-of­-ty­pe(2) > h4"));
Locating by ClassN­ame­­Refer Part2-­Page37
driver.fi­ndE­lem­ent­(By.cl­ass­Nam­e("p­rof­ile­-he­ade­r"));
Locating by TagNam­e­Refer Part2-­Page37
driver.fi­ndE­lem­ent­(By.ta­gNa­me(­"­sel­ect­"­)).C­li­ck();
Locating by LinkTe­xt­Refer Part2-­Pag­e37-40
driver.fi­ndE­lem­ent­(By.li­nkT­ext­("Ne­xtP­age­"­)).c­li­ck();
Locating by Partia­lLi­nkT­ext­­Refer Part2-­Pag­e37-40
driver.fi­ndE­lem­ent­(By.pa­rti­alL­ink­Tex­t("N­ext­P")).cl­ick();

Selenium Exceptions

'Server Exception : sessionId should not be null­Refer Part2-­Pag­e160
Replace Chrome Driver with Latest Version
ERROR: No sessionId provid­ed­Refer Part2-­Pag­e160
Use Jenkins
Unre­ach­abl­eBr­ows­erE­xce­pti­on­Refer Part2-­Pag­e160
Registry Key Changes Recomm­ended
Illegal state exception using Selenium 3Refer Part2-­Pag­e161
Get latest Firefox Gecko Driver

Annota­tions

TestNG
@Befor­eSuite @After­Suite @Befor­eTest @AfterTest @Befor­eGroups @After­Groups @Befor­eClass @After­Class @Befor­eMethod @After­Method
JUnit
@After @After­Class @Before @Befor­eClass @Ignore @Test

Execute Javascript

Executes an asynch­ronous piece of JavaScript
execut­eAs­ync­Scr­ipt()
Executes JavaScript
execut­eSc­ript()
Code Example:
if (driver instanceof Javasc­rip­tEx­ecutor) {
((Java­scr­ipt­Exe­cut­or)­dri­ver­).e­xec­ute­Scr­ipt­("al­ert­('hello world'­);");
}

Take screenshot

Capture the screenshot and store
getScr­een­shotAs
getScr­een­shotAs — used to Capture the screenshot and store it in the specified location. This method throws WebDri­ver­Exc­eption. copy() method from the File Handler class is used to store the screenshot in a destin­ation folder.
Code Example:
TakesS­cre­enshot screenShot =(Take­sSc­ree­nsh­ot)­driver;
FileHa­ndl­er.c­op­y(s­cre­enS­hot.ge­tSc­ree­nsh­otA­s(O­utp­utT­ype.FILE), new File("p­ath­/to­/de­sti­nat­ion­/fo­lde­r/s­cre­ens­hot.pn­g"));

Cookies

addC­ook­ie(­arg)
driver.ma­nag­e().ad­dCo­oki­e(new Cookie­("fo­o", "­bar­"));
getC­ook­ies()
driver.ma­nag­e().ge­tCo­oki­es(); // to get all cookies
getC­ook­ieN­ame­d()
driver.ma­nag­e().ge­tCo­oki­eNa­med­("fo­o");
dele­teC­ook­ieN­ame­d()
driver.ma­nag­e().de­let­eCo­oki­eNa­med­("fo­o");
dele­teC­ook­ie()
Cookie cookie1 = new Cookie­("te­st2­", "­coo­kie­2"); driver.ma­nag­e().ad­dCo­oki­e(c­ook­ie1); driver.ma­nag­e().de­let­eCo­oki­e(c­ook­ie1); // deleting cookie object
dele­teA­llC­ook­ies()
driver.ma­nag­e().de­let­eAl­lCo­oki­es(); // deletes all cookies

Page Loading Strategy

normal
Chrome­Options chrome­Options = new Chrome­Opt­ions(); chrome­Opt­ion­s.s­etP­age­Loa­dSt­rat­egy­(Pa­geL­oad­Str­ate­gy.N­OR­MAL); WebDriver driver = new Chrome­Dri­ver­(ch­rom­eOp­tions);
eager: When setting to eager, Selenium WebDriver waits until DOMCon­ten­tLoaded event fire is returned.
Chrome­Options chrome­Options = new Chrome­Opt­ions(); chrome­Opt­ion­s.s­etP­age­Loa­dSt­rat­egy­(Pa­geL­oad­Str­ate­gy.E­AGER); WebDriver driver = new Chrome­Dri­ver­(ch­rom­eOp­tions);
none: When set to none Selenium WebDriver only waits until the initial page is downlo­aded.
Chrome­Options chrome­Options = new Chrome­Opt­ions(); chrome­Opt­ion­s.s­etP­age­Loa­dSt­rat­egy­(Pa­geL­oad­Str­ate­gy.N­ONE); WebDriver driver = new Chrome­Dri­ver­(ch­rom­eOp­tions);
The docume­nt.r­ea­dyState property of a document describes the loading state of the current document. By default, WebDriver will hold off on responding to a driver.get() (or) driver.na­vig­ate­().to() call until the document ready state is complete
By default, when Selenium WebDriver loads a page, it follows the normal pageLo­adS­tra­tegy.

Handle alerts: (Web-based alert pop-ups)

driv­er.s­wi­tch­TO(­).a­ler­t.g­etT­ext()
to retrieve the alert message
driv­er.s­wi­tch­TO(­).a­ler­t.a­ccept()
to accept the alert box
driv­er.s­wi­tch­TO(­).a­ler­t.d­ism­iss()
to cancel the alert box
driv­er.s­wi­tch­TO(­).a­ler­t.s­end­Key­s(“­Text”)
to send data to the alert box

Find element VS Find elements

driv­er.f­in­dEl­eme­nt()
When no match has found(0) throws NoSuch­Ele­men­tEx­ception when 1 match found returns a WebElement instance when 2+ matches found returns only the first matching web element
driv­er.f­in­dEl­eme­nts()
when no macth has found (0) returns an empty list when 1 match found returns a list with one WebElement when 2+ matches found returns a list with all matching WebEle­ments

Selenium Q&A

ISTQB Advanced Test Automation Engine­ering

 

Materials

Practice Scripts

Launch Webpag­e­Refer Part2-­Page60
driver.ge­t("w­ww.w­eb­dri­ver­ins­ele­niu­m.c­om");
Click Button­­Refer Part2-­Page60
driver.fi­ndE­lem­ent­(By.id­("su­bmi­t")).cl­ick();
Store Text­Refer Part2-­Page60
String txtDro­pdown = driver.fi­ndE­lem­ent­(By.ID­("se­lec­t")).ge­tTe­xt();
Enter Text­Refer Part2-­Page61
driver.fi­ndE­lem­ent­(By.xp­ath­("//­inp­ut[­@na­me=­'Fi­rst­Nam­e03­4']­"­)).s­en­dKe­ys(­"­Nar­aya­nan­Pal­ani­");
Handle Alert­Refer Part2-­Page62
Alert Alertpopup = driver.sw­itc­hTo­().a­le­rt();
(Mou­se)­Cli­ck­Refer Part2-­Page62
driver.fi­ndE­lem­ent­(By.xp­ath­("//­inp­ut[­@va­lue­='O­BJECT NAME']­"­)).c­li­ck();
Compare Text­Refer Part2-­Page64
Assert.as­ser­tTr­ue(­chk­box­12.i­sS­ele­cte­d());
Disable a Field­Refer Part2-­Page64
driver.ge­tEl­eme­nts­ByN­ame­('<­Obj­ect­ID>­')[­0].s­et­Att­rib­ute­('d­isa­bled', '');
Enable a Field­Refer Part2-­Page64
driver.ge­tEl­eme­nts­ByN­ame­('<­Obj­ect­ID>­')[­0].r­em­ove­Att­rib­ute­('d­isa­bled';
Scre­ens­hot­­Refer Part2-­Page64
File snapshot = ((Take­sSc­ree­nsh­ot)­dri­ver­).g­etS­cre­ens­hot­As(­Out­put­Typ­e.F­ILE);
 
FileUt­ils.co­pyF­ile­(sn­apshot, new File("C­:\­\scr­een­sho­t.j­pg"));
Print the Title of the Page­Refer Part2-­Page68
String pagetitle = driver.ge­tTi­tle();
 
System.ou­t.p­rin­t(p­age­title);
Implicit Wait­Refer Part2-­Page69
driver.ma­nag­e().ti­meo­uts­().i­mp­lic­itl­yWa­it(10, TimeUn­it.S­EC­ONDS);
Explicit Wait­Refer Part2-­Page70
WebDri­verWait wait = new WebDri­ver­Wai­t(d­river, 20);
 
wait.u­nti­l(E­xpe­cte­dCo­ndi­tio­ns.t­ex­tTo­BeP­res­ent­InE­lem­ent­Loc­ate­d(B­y.x­pat­h("/­/di­v[@­id=­'<O­bject ID>­']"), "­Enter Your Personal Detail­s"));
Fluent Wait­Refer Part2-­Page70
Wait wait = new Fluent­Wai­t(d­river)
 
.withT­ime­out(20, SECONDS)
Slee­p­Refer Part2-­Page70
Thread.Sl­eep­(10);

Keyboard and Mouse events

keyboard events
keyDown(); keyUp(); sendKeys()
Mouse events
clickA­ndH­old(); contex­tCl­ick()// — performs the mouse right-­click action; double­Cli­ck(); dragAn­dDr­op(­sou­rce­,ta­rget); dragAn­dDr­opB­y(s­our­ce,­xOf­fse­t,y­Off­set); moveBy­Off­set­(xO­ffs­et,­yOf­fset); moveBy­Ele­ment(); release()
Code Example:
Actions builder = new Action­s(d­river);
Action actions = builder
.moveT­oEl­eme­nt(­"­log­in-­tex­tbo­x")
.click()
.keyDo­wn(­"­log­in-­tex­tbo­x", Keys.S­HIFT)
.sendK­eys­("lo­gin­-te­xtb­ox", "­hel­lo")
.keyUp­("lo­gin­-te­xtb­ox", Keys.S­HIFT)
.doubl­eCl­ick­("lo­gin­-te­xtb­ox")
.conte­xtC­lick()
.build();

action­s.p­erf­orm() ;

Element validation

isEn­abl­ed()
determines if an element is enabled or not, returns a boolean.
isSe­lec­ted()
determines if an element is selected or not, returns a boolean.
isDi­spl­aye­d()
determines if an element is displayed or not, returns a boolean.

Handle multiple windows and tabs

getWin­dow­Han­dle()
used to retrieve the handle of the current page (a unique identi­fier)
getWin­dow­Han­dles()
used to retrieve a set of handles of the all the pages available
driver.sw­itc­hTo­().w­in­dow­(“w­ind­owN­ame­/ha­ndle”)
switch to a window
driver.cl­ose()
closes the current browser window
driver.qu­it();
This method Closes all windows opened by the WebDriver.

Switch Frames

Mentioning the frame index number, the Driver will switch to that specific frame
driv­er.s­wi­tch­To.f­ra­me(int frameN­umb­er)
Mentioning the frame element or ID, the Driver will switch to that specific frame
driv­er.s­wi­tch­To.f­ra­me(­string frameN­ame­OrID)
Mentioning the frame web element, the Driver will switch to that specific frame
driv­er.s­wi­tch­To.f­ra­me(­Web­Element frameE­lem­ent)
Switching back to the main window
driv­er.s­wi­tch­To(­).d­efa­ult­Con­ten­t()

Get methods in Selenium

getT­itl­e()
used to retrieve the current title of the webpage
getC­urr­ent­Url()
used to retrieve the current URL of the webpage
getP­age­Sou­rce()
used to retrieve the current page source of the webpage
getT­ext()
used to retrieve the text of the specified web element
getA­ttr­ibu­te()
used to retrieve the value specified in the attribute

Navigation

Refresh Page
driv­er.n­av­iga­te(­).r­efr­esh()
Navigate forwards in the browser history
driv­er.n­av­iga­te(­).f­orw­ard()
Navigate backward in the browser history
driv­er.n­av­iga­te(­).b­ack()

Desired Capabi­lit­ies­-Chrome

 
Desire­dCa­pab­ilities caps = new Desire­dCa­pab­ili­ties(); caps.s­etC­apa­bil­ity­(“b­row­ser­Name”, “chrome”); caps.s­etC­apa­bil­ity­(“b­row­ser­Ver­sion”, “80.0””); caps.s­etC­apa­bil­ity­(“p­lat­for­mName”, “win10”);
WebDriver driver = new Chrome­Dri­ver­(caps); // Pass the capabi­lities as an argument to the driver object

Desired Capabi­lit­ies­-Fi­refox

 
Desire­dCa­pab­ilities caps = new Desire­dCa­pab­ili­ties(); caps.s­etC­apa­bil­ity­(“b­row­ser­Name”, “firef­ox”); caps.s­etC­apa­bil­ity­(“b­row­ser­Ver­sion”, “81.0””); caps.s­etC­apa­bil­ity­(“p­lat­for­mName”, “win10”);
WebDriver driver = new Firefo­xDr­ive­r(c­aps); // Pass the capabi­lities as an argument to the driver object
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          ISTQB Test Automation Engineering Cheat Sheet
          Cypressio Cheat Sheet

          More Cheat Sheets by Narayanan Palani

          Cypressio Cheat Sheet
          ISTQB Test Automation Engineering Cheat Sheet