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) https://engineers-hub.teachable.com/

Driver Initia­liz­ation

Firefox (Below v.47)Refer 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();
ChromeRefer 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 ExplorerRefer 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 NameRefer Part2-­Page37
driver.fi­ndE­lem­ent­(By.na­me(­"­q")).se­ndK­eys­("Se­lenium 3");
Locating by XpathRefer 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 DOMRefer Part2-­Page39
dom =docum­ent.ge­tEl­eme­ntB­yId­('s­ign­inF­orm')
Locating by CSSRefer 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 ClassNameRefer Part2-­Page37
driver.fi­ndE­lem­ent­(By.cl­ass­Nam­e("p­rof­ile­-he­ade­r"));
Locating by TagNameRefer Part2-­Page37
driver.fi­ndE­lem­ent­(By.ta­gNa­me(­"­sel­ect­"­)).C­li­ck();
Locating by LinkTextRefer Part2-­Pag­e37-40
driver.fi­ndE­lem­ent­(By.li­nkT­ext­("Ne­xtP­age­"­)).c­li­ck();
Locating by Partia­lLi­nkTextRefer Part2-­Pag­e37-40
driver.fi­ndE­lem­ent­(By.pa­rti­alL­ink­Tex­t("N­ext­P")).cl­ick();

ISTQB Advanced Test Automation Engine­ering

Selenium Q&A

Find element VS Find elements

driver.fi­ndE­lem­ent()
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
driver.fi­ndE­lem­ents()
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

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

driver.sw­itc­hTO­().a­le­rt.g­et­Text()
to retrieve the alert message
driver.sw­itc­hTO­().a­le­rt.a­cc­ept()
to accept the alert box
driver.sw­itc­hTO­().a­le­rt.d­is­miss()
to cancel the alert box
driver.sw­itc­hTO­().a­le­rt.s­en­dKe­ys(­“Text”)
to send data to the alert box

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.

Cookies

addCoo­kie­(arg)
driver.ma­nag­e().ad­dCo­oki­e(new Cookie­("fo­o", "­bar­"));
getCoo­kies()
driver.ma­nag­e().ge­tCo­oki­es(); // to get all cookies
getCoo­kie­Named()
driver.ma­nag­e().ge­tCo­oki­eNa­med­("fo­o");
delete­Coo­kie­Named()
driver.ma­nag­e().de­let­eCo­oki­eNa­med­("fo­o");
delete­Coo­kie()
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
delete­All­Coo­kies()
driver.ma­nag­e().de­let­eAl­lCo­oki­es(); // deletes all cookies

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"));

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'­);");
}

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

Selenium Exceptions

'Server Exception : sessionId should not be nullRefer Part2-­Page160
Replace Chrome Driver with Latest Version
ERROR: No sessionId providedRefer Part2-­Page160
Use Jenkins
Unreac­hab­leB­row­ser­Exc­eptionRefer Part2-­Page160
Registry Key Changes Recomm­ended
Illegal state exception using Selenium 3Refer Part2-­Page161
Get latest Firefox Gecko Driver
 

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

isEnab­led()
determines if an element is enabled or not, returns a boolean.
isSele­cted()
determines if an element is selected or not, returns a boolean.
isDisp­layed()
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
driver.sw­itc­hTo.fr­ame(int frameN­umber)
Mentioning the frame element or ID, the Driver will switch to that specific frame
driver.sw­itc­hTo.fr­ame­(string frameN­ame­OrID)
Mentioning the frame web element, the Driver will switch to that specific frame
driver.sw­itc­hTo.fr­ame­(We­bEl­ement frameE­lement)
Switching back to the main window
driver.sw­itc­hTo­().d­ef­aul­tCo­ntent()

Materials

Get methods in Selenium

getTitle()
used to retrieve the current title of the webpage
getCur­ren­tUrl()
used to retrieve the current URL of the webpage
getPag­eSo­urce()
used to retrieve the current page source of the webpage
getText()
used to retrieve the text of the specified web element
getAtt­rib­ute()
used to retrieve the value specified in the attribute

Navigation

Refresh Page
driver.na­vig­ate­().r­ef­resh()
Navigate forwards in the browser history
driver.na­vig­ate­().f­or­ward()
Navigate backward in the browser history
driver.na­vig­ate­().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

Practice Scripts

Launch WebpageRefer Part2-­Page60
driver.ge­t("w­ww.w­eb­dri­ver­ins­ele­niu­m.c­om");
Click ButtonRefer Part2-­Page60
driver.fi­ndE­lem­ent­(By.id­("su­bmi­t")).cl­ick();
Store TextRefer Part2-­Page60
String txtDro­pdown = driver.fi­ndE­lem­ent­(By.ID­("se­lec­t")).ge­tTe­xt();
Enter TextRefer 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 AlertRefer Part2-­Page62
Alert Alertpopup = driver.sw­itc­hTo­().a­le­rt();
(Mouse­)ClickRefer Part2-­Page62
driver.fi­ndE­lem­ent­(By.xp­ath­("//­inp­ut[­@va­lue­='O­BJECT NAME']­"­)).c­li­ck();
Compare TextRefer Part2-­Page64
Assert.as­ser­tTr­ue(­chk­box­12.i­sS­ele­cte­d());
Disable a FieldRefer Part2-­Page64
driver.ge­tEl­eme­nts­ByN­ame­('<­Obj­ect­ID>­')[­0].s­et­Att­rib­ute­('d­isa­bled', '');
Enable a FieldRefer Part2-­Page64
driver.ge­tEl­eme­nts­ByN­ame­('<­Obj­ect­ID>­')[­0].r­em­ove­Att­rib­ute­('d­isa­bled';
ScreenshotRefer 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 PageRefer Part2-­Page68
String pagetitle = driver.ge­tTi­tle();
 
System.ou­t.p­rin­t(p­age­title);
Implicit WaitRefer Part2-­Page69
driver.ma­nag­e().ti­meo­uts­().i­mp­lic­itl­yWa­it(10, TimeUn­it.S­EC­ONDS);
Explicit WaitRefer 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 WaitRefer Part2-­Page70
Wait wait = new Fluent­Wai­t(d­river)
 
.withT­ime­out(20, SECONDS)
SleepRefer Part2-­Page70
Thread.Sl­eep­(10);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
 

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

          Cypressio Cheat Sheet
          ISTQB Test Automation Engineering Cheat Sheet

          More Cheat Sheets by Narayanan Palani

          Cypressio Cheat Sheet
          ISTQB Test Automation Engineering Cheat Sheet