+ All Categories
Home > Documents > Top 20 Useful Commands in Selenium Webdriver

Top 20 Useful Commands in Selenium Webdriver

Date post: 05-Jul-2018
Category:
Upload: pavan-pawan
View: 236 times
Download: 0 times
Share this document with a friend

of 25

Transcript
  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    1/25

    Selenium Xpath Tutorials

    Identifying xpath for element with examples to use in selenium

    QA Engineers need to provide any element locator(like id name css path

    xpath etc!" in target column of selenium window to locate that speci#c elementto perform some action on it !If you have worked with selenium I$E then youknows that sometimes elements does not contains id or name! %ocatingelement &y xpath is the another way of locating element and you can use it asa alternative of id or name of element!

    Xpath in X'% document shows the direction of element location through nodesand attri&utes! %et we try to understand how to identify Xpath of element withexamples!

     

    A&ove given image is taken from http))www!wikipedia!org)! There are three#elds *! Input text &ox +! Select dropdown and ,! Input &utton! And &ellowof those #elds there is expansion of relative X'% nodes through #re&ug! Asyou see in image you can use-id.searchInput- or -name.search- toidentify input text &ox to typesomething in to it as &ellow givenexample!

    /omma

    nd

    Target 0alue

    /ommand

    Target 0alue

    1penhttp))www!wikipedia!org

     

    Type name.search

    SeleniumAutomat

    ion

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    2/25

    1penhttp))www!wikipedia!org

     

    Type id.searchInput

    SeleniumAutomation

    Xpath Element Identi#cation

    %ocating element using Xpath with Examples for input text &ox

     XpathTechni2ues

    Examples Explanations

    *

    IdentifyingXpath

    usingfull pathof X'%

    xpath.))&ody)div3,4)form)#eldset)in

    put3+4

    ))&ody is themain rootnode )div3,4descri&es the,rd div childnode of parentnode &ody)formdescri&es thechild nodeform of parent

    node div3,4)#eldsetdescri&es thechild node#eldset ofparent nodeform )input3+4descri&es the+nd input childnode of parentnode #eldset!

    +

    5rittingXpathusinglast("

    xpath.))&ody)div3,4)form)#eldset)input3last("6+4

    )input3last("6+4

    descri&es the,rd upperinputnode(input3+4"from last inputnode!

    ,

    5rittingXpathusinglast("

    xpath.))&ody)div3,4)form)#eldset)73last("6,4

    )73last("6,4descri&es the8th uppernode(input3+4"from last node!

    8 Xpath xpath.))&ody)div3,4)form)#eldset)in )

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    3/25

    locatorusing 9andattri&ut

    e

    put39type.:search:4

    input39type.:search:4descri&es theinput nodehaving

    attri&utetype.:search:

    ;

    Xpathexpression using9 andattri&ute

    xpath.))&ody)div3,4)form)#eldset)input39accesskey.:

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    4/25

    keyword -searchInput-

    *

    Xpathusingand withattri&utes

    xpath.))input3contains(9id-searchInput-" andcontains(9accesskey-

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    5/25

    +nd childelement of#eldset whichis input3+4

    *;

    BsingText(" to#ndelement

    xpath.))div)a3text(".-English-4This will #nd alink that hastext .-English-

    Xpath examples for drop down

    *! xpath.))&ody)div3,4)form)#eldset)select+! xpath.))&ody)div3,4)form)#eldset)select3last("4,!xpath.))&ody)div3,4)form)#eldset)select39id.:search%anguage:48! xpath.))&ody)div3,4)form)#eldset)select39name.:language:4;! xpath.))div39class.:search6container:4)descendantselect39name.:language:4=! xpath.))select3contains(9id -search%anguage-"4>! xpath.))div39class.:search6container:4)descendantselect3position(".*4?! xpath.))&ody)div3,4)form)#eldset)select3count(7"G*4 

    1ther Xpath Example

    *!

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    6/25

    1. /reating Lew Instance 1f ?id=@ti'e,eft@")8 "i'e left seconds"));Above 2 syntax will wait for till 14 seconds for ex!ected text "i'e left seconds" to bea!!ear on targeted ele'ent.

    B. Net page title in selenium we&driver

    driver.getitle();t will retrieve !age title and yo/ can store it in variable to /se in next ste!s.

    C. Net /urrent Jage BC% In Selenium 5e&$river

    driver.get9/rrent*rl();t will retrieve c/rrent !age *+, and yo/ can /se it to co'!are wit yo/r ex!ected *+,.

    1%. Net domain name using Oava script executor

     avascri!t-xec/tor Eavascri!t = (avascri!t-xec/tor) driver;tring 9/rrent*+,*sing=(tring)Eavascri!t.exec/tecri!t("ret/rn doc/'ent.do'ain");Above syntax will retrieve yo/r software a!!lication@s do'ain na'e /sing webdriver@s Eava scri!t exec/tor interface and store it in to variable.

    11. Nenerate alert using we&driver:s Oava script executor interface

     avascri!t-xec/tor Eavascri!t = (avascri!t-xec/tor) driver;

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    7/25

     Eavascri!t.exec/tecri!t("alert(@est 9ase -xec/tion s started 3ow..@);");t will generate alert d/ring yo/r seleni/' webdriver test case exec/tion.

    12. Selecting or $eselecting value from drop down in selenium we&driver! elect y Gisible ext

    elect 'ydr!dwn = new elect(driver.nd-le'ent(y.id("9arlist")));'ydr!dwn.selectyGisibleext("A/di");t will select val/e fro' dro! down list /sing visible text val/e = "A/di". elect y Gal/eelect listbox = new elect(driver.nd-le'ent(y.x!at("##select>?na'e=@Fro',@")));listbox.selectyGal/e("taly");t will select val/e by val/e = "taly". elect y ndexelect listbox = new elect(driver.nd-le'ent(y.x!at("##select>?na'e=@Fro',@")));listbox.selectyndex(%);t will select val/e by index= %(First o!tion).

    Deselect by Gisible ext

    elect listbox = new elect(driver.nd-le'ent(y.x!at("##select>?na'e=@Fro',@")));listbox.deselectyGisibleext("+/ssia");t will deselect o!tion by visible text = +/ssia fro' list box. Deselect by Gal/eelect listbox = new elect(driver.nd-le'ent(y.x!at("##select>?na'e=@Fro',@")));listbox.deselectyGal/e("6exico");t will deselect o!tion by val/e = 6exico fro' list box. Deselect by ndexelect listbox = new elect(driver.nd-le'ent(y.x!at("##select>?na'e=@Fro',@")));listbox.deselectyndex(4);t will deselect o!tion by ndex = 4 fro' list box. Deselect Allelect listbox = new elect(driver.nd-le'ent(y.x!at("##select>?na'e=@Fro',@")));listbox.deselectAll();t will re'ove all selections fro' list box.

    is6/lti!le()elect listbox = new elect(driver.nd-le'ent(y.x!at("##select>?na'e=@Fro',@")));boolean val/e = listbox.is6/lti!le();t will ret/rn tr/e if select box is '/ltiselect else it will ret/rn false.

    1&. Lavigate to BC% or Mack or

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    8/25

    File*tils.co!yFile(screensot8 new File("DJJscreensot.E!g"));t will ca!t/re !age screensot and store it in yo/r D drive.

    17. Nenerating 'ouse Fover Event In 5e&$river

    Actions actions = new Actions(driver);

    Web-le'ent 'oveon'en/ = driver.nd-le'ent(y.x!at("##div>?id=@'en/1@#div"));actions.'oveo-le'ent('oveon'en/);actions.!erfor'();Above exa'!le will 'ove 'o/se on targeted ele'ent.

     1. Fandling 'ultiple 5indows In Selenium 5e&$river!1. Ket All Window Landles.etMtringN AllWindowLandles = driver.getWindowLandles();2. -xtract !arent and cild window andle fro' all window andles.tring window1 = (tring) AllWindowLandles.toArray()>%;tring window2 = (tring) AllWindowLandles.toArray()>1;&. *se window andle to switc fro' one window to oter window.driver.switco().window(window2);

    Above given ste!s wit el!s yo/ to get window andle and ten ow to switc fro' onewindow to anoter window

    1B. /heck 5hether Element is Ena&led 1r $isa&led In Selenium 5e& driver!

    boolean fna'e = driver.nd-le'ent(y.x!at("##in!/t>?na'e=@fna'e@")).is-nabled();yste'.o/t.!rint(fna'e);Above syntax will verify tat ele'ent (text box) fna'e is enabled or not. Oo/ can /se itfor any in!/t ele'ent.

     1C. Ena&le)$isa&le Text&ox $uring Selenium 5e&driver Test /ase Execution! avascri!t-xec/tor Eavascri!t = (avascri!t-xec/tor) driver;tring todisable = "doc/'ent.get-le'entsy3a'e(@fna'e@)>%.setAttrib/te(@disabled@8@@);"; Eavascri!t.exec/tecri!t(todisable);tring toenable = "doc/'ent.get-le'entsy3a'e(@lna'e@)>%.re'oveAttrib/te(@disabled@);"; Eavascri!t.exec/tecri!t(toenable);t will disable fna'e ele'ent /sing setAttrib/te() 'etod and enable lna'e ele'ent/sing re'oveAttrib/te() 'etod.

     2%. Selenium 5e&$river Assertions 5ith TestLN

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    9/25

    i'!ort org.o!enPa.seleni/'.WebDriver;i'!ort org.o!enPa.seleni/'.cro'e.9ro'eDriver;i'!ort org.o!enPa.seleni/'.refox.FirefoxDriver;i'!ort org.o!enPa.seleni/'.ie.nternet-x!lorerDriver;i'!ort org.testng.annotations.After6etod;

    i'!ort org.testng.annotations.efore6etod;i'!ort org.testng.annotations.

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    10/25

      M#testN  Mtest na'e="9ro'eest"N  M!ara'eter na'e="browser" val/e="cro'e" #N  MclassesN  Mclass na'e="6/ltirowser" #N  M#classesN

      M#testN  Mtest na'e="-est"N  M!ara'eter na'e="browser" val/e="iex!lorer" #N  MclassesN  Mclass na'e="6/ltirowser" #N  M#classesN  M#testNM#s/iteN

    ,! Low run the code from TestLN!xml

     Oo/ can observer all te tree browsers will o!en and !erfor' te tas0 at a ti'e.

    Selenium WebDriver methods with ExamplesSelenium WebDriver methods with Examples

    1.Browser Back and Forward (N!"#$"%N&

    Steps to implement Browser back and forward through Selenium Web Driver

    1. Create Driver for any Browser(o!illa"

    #. $o to the %&'

    . )avigate to some page in website.

    *. %se Selenium code to )avigate Back to ain +age.

    '%DE driver.navigate().back();  driver.navigate().forward();

    Example

    WebDriver driver new !irefoxDriver();

    driver.get("http#$$seleniumh%.org$");

    driver.findElement(&'.linkext("Download")).click();

    hread.sleep(***); $$dela'

    driver.navigate().back();

    driver.navigate().forward();

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    2.Handling DRAG and DROP

    Steps to ,andle Drag and Drop through Selenium Web Driver

    1. Create Driver for any Browser(o!illa"

    #. $o to the %&'

    . Create an -ction obect for Driver

    *. /etch and create Web0lement obect for the S%&C0 element.

    2. /etch and create Web0lement obect for the D0S34)-34) element.

    5.+erform -C34)

      1.Click and ,old the source Web0lement

      #.ove to destination Web0lement

      .&elease the 0lement.

    Example

    WebDriver driver 6 new /irefo7Driver("8driver.get(9http:;;www.ericbieller.com;e7amples;dragdrop;9"8

    http://selenium-suresh.blogspot.com/2013/09/selenium-webdriver-methods-with-examples.htmlhttp://selenium-suresh.blogspot.com/2013/09/selenium-webdriver-methods-with-examples.html

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    11/25

    driver.manage(".timeouts(".implicitlyWait(id6?items?@;div=1@9""8Web0lement des 6 driver.find0lement(By.id(9trash9""8 

    act.click-nd,old(src".build(".perform("8 ;;/or each action we need to build and +erformact.move3o0lement(des".build(".perform("8act.release(des".build(".perform("8++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    ).*akin+ Sin+le Select in Drop down (%ption ,ist&

    Steps to make Single Select in Drop down through Selenium Web Driver.

    1. Create Driver for any Browser(o!illa"#. $o to the %&'. /etch the Drop Down element and create an obect as Web0lement.*. Create an Select obect for the Drop Down 0lement obect.2. Create a 'ist and collect all ptions through Select bect.5. Create a 4terator obect for the 'ist.

    A. $et the si!e of the 'ist.. 'oop through and check for reuired element.

    Example

    Web0lement element 6 driver.find0lement(By.name(9selectedCustomer9""8Select dd6 new Select(element"8'ist allptions6 dd.getptions("8

     ;;3o go through the list< we can use an 4terator. ;;4terator should be of the same type as the 'ist ;;which is Web0lement in this case.

    4terator it 6 allptions.iterator("8

     ;;%sing while loop< we can iterate till the 'ist has ;;a ne7t Web0lement =has)e7t(" is true@ ;;number of items in the listSystem.out.println(allptions.si!e(""8

    while(it.has)e7t("" ;;When you say it.ne7t("< it points to a particular ;;Web0lement in the 'ist.Web0lement el 6 it.ne7t("8 ;;Check for the reuired element by 3e7t and click itif(el.get3e7t(".euals(9mango9""  System.out.println(el.get-ttribute(9value9""8  el.click("8

    EE++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    -.*akin+ Sin+le Select in Drop down (B "NDE/0 !,E0 $E/$&Steps to make Single Select in Drop down through Selenium Web Driver.

    1. Create Driver for any Browser(o!illa"

    #. $o to the %&'

    . /etch the Drop Down element and create an obect as Web0lement.

    *. Convert the Drop Down 0lement in to Select obect.

    2. Select by 4)D0F

    5. Select by G-'%0

    A. Select by G4S4B'0 30F3

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    12/25

    Example

    Web0lement customerdd 6 driver.find0lement(By.name(9customer+roect.shownCustomer9""8

      ;;convert the element to select obect

      Select cust 6 new Select(customerdd"8

      cust.selectBy4nde7(1"8 ;;Select by 4nde7

      3hread.sleep(HHH"8

      cust.selectByGalue(9#9"8 ;;Select by Galue

      3hread.sleep(HHH"8

      cust.selectByGisible3e7t(9mango9"8 ;;Select by Gisible 3e7t

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    2.*ultiple Select ,ist Box Window

    Steps to make ultiple Select in Drop down through Selenium Web Driver.

    1. Create Driver for any Browser(o!illa"

    #. $o to the %&'

    . /etch the Drop Down element and create an obect as Web0lement.

    *. Convert the Drop Down 0lement in to Select obect.

    2. Select by 4nde7(Start inde7"

    5. Select by 4nde7(0nd inde7"

    Example

    WebElement userdd driver.findElement(&'.name("users"));

    Select usr new Select(userdd);

    usr.select&',ndex(*); $$Select b' ,ndex(!rom Start location)

    usr.select&',ndex(-); $$Select b' index(o End ocation)

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    3.*ultiple Select ,ist Box Window 4 DESE,E'$

    Steps to make Deselect in Drop down through Selenium Web Driver.

    1. Create Driver for any Browser(o!illa"

    #. $o to the %&'

    . /etch the Drop Down element and create an obect as Web0lement.

    *. Convert the Drop Down 0lement in to Select obect.

    2. Select by 4nde7(Start inde7"

    5. Select by 4nde7(0nd inde7"

    Example

    WebElement userdd driver.findElement(&'.name("users"));

    Select usr new Select(userdd);

    usr.select&',ndex(*);

    usr.select&',ndex(-);

    $$/ou can deselect the optionsusr.deselect0ll(); $$Deselect 0 selected elements

    $$or

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    13/25

    usr.deselect&',ndex(*); $$Deselect &' using ,ndex

    $$or 

    usr.deselect&'1alue(value); $$Deselect &' using 1alue

    $$or 

    usr.deselect&'1isibleext(text); $$Deselect &' using ext

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    5.iF6*ES 4 7ow to handle Frames in Web Driver 

    Steps to get Source of each i/rame through Selenium Web Driver.

    1. Create Driver for any Browser(o!illa"

    #. $o to the %&'

    . ake a 'ist containing /&-0 web elements of a Web +age.

    *. $et the Si!e of /rames.

    2. 'oop though and print the Source of each /rame

    Example

     ;Itimes of india website J multiple framesI;

    driver.get(9http:;;timesofindia.indiatimes.com;9"8

    driver.manage(".timeouts(".implicitlyWait(H< 3ime%nit.S0C)DS"8

    'ist frms6 driver.find0lements(By.tag)ame(9iframe9""8 ;;/rame 'ist

    System.out.println(frms.si!e(""8

    for(int i6H8i

     System.out.println(frms.get(i".get-ttribute(9src9""8

    E++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    8.iF6*ES 4 7ow to per9orm action in Frames

    Steps to perform -ction in i/rame through Selenium Web Driver.

    1. Create Driver for any Browser(o!illa"

    #. $o to the %&'

    . /etch i/rame element and create an Web 0lement obect.

    *. %sing i/rame Web 0lement obect< switch to 4/rame.

    2. +erform SendKeys; Click action in i/rame.

    Example

    WebElement ifr driver.findElement(&'.xpath("$$iframe23src4$poll.cms45"));

    driver.switcho().frame(ifr); $$Switch to i!rame

    driver.findElement(&'.id("mathuserans-")).send6e's("7"); $$8erform 0ction in i!rame

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    :.iF6*ES 4 7ow to switch to a perticular Frame throu+h index

    Steps to switch to perticular i/rame by inde7 through Selenium Web Driver.

    1. Create Driver for any Browser(o!illa"

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    14/25

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    15/25

    Set window9andles driver.getWindow9andles();

    ,terator it window9andles.iterator();

    String parent&rowser it.next();

    String child&rowser it.next();

    driver.switcho().window(child&rowser);

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    $BS

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    16/25

     ;I4&C3C calendarI;

    driver.find0lement(By.id(9calendarLicon19"".click("8

    driver.find0lement(By.7path(9;;div=>id6?CalendarControl?@;table=tbody=tr=td=te7t("6?ctober

    #H1#?@@@@;descendant::a=te7t("6?2?@9"".click("8

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    'alendar >opp 4 = ('ustomi?ed wait&

     4n a Calender if we want to click on future month which is not currently displayed< we need to

    click on ne7t link until we get the reuired month.

      3his can be done by writing Customi!ed wait. Check for particular date element in each

    month< if not found move to ne7t month.

     ;Imakemytrip calendarI;

    driver.get(9http:;;www.makemytrip.com;9"8

    driver.manage(".timeouts(".implicitlyWait(H< 3ime%nit.S0C)DS"8

    driver.find0lement(By.id(9deptDate&tripimg07act9"".click("8 ;;find Calendar

    driver.manage(".timeouts(".implicitlyWait(H< 3ime%nit.S0C)DS"8

    boolean flag6true8

    while(flag"

      try

     Web0lement el 6 driver.find0lement(By.7path(9;;div=contains(>class

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    17/25

    #. $o to the %&'

    . /etch the 0)% +arent element and create a Web0lement obect.

    *. Create an -ction obect for Driver

    2. 3hrough -ction obect< move to +arent element.

    5. $ive a Delay for menu items to be displayed.

    A. /etch the Child item through 7path and Click on it.

    Web0lement parentenu 6 driver.find0lement(By.link3e7t(93ourist 3rains9""8

    -ctions act 6 new -ctions(driver"8 ;; Create an -ction obect

     ;;move to the parent menu item

    act.move3o0lement(parentenu".build(".perform("8

    3hread.sleep(HHH"8 ;;wait till the child items are displayed

    driver.find0lement(By.link3e7t(9Bharat 3irth9"".click("8

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    1). 'ontext 'lick (6i+ht 'lick&

    We can use keyboard keys to ake a &ight Click.

    +lease follow the steps mentioned below.

    1. Create Driver for any Browser(o!illa".

    #. $o to the %&'.

    . /etch the 0)% +arent element and create a Web0lement obect.

    *. Create an -ction bect for Driver.

    2. 3hrough -ction bect< make a Conte7t Click on enu +arent obect.

    5. 3hrough -ction bect< send keys for -&&WLDW);-&&WL%+;Keys.0)30&.

    Example

    Web0lement parentenu 6 driver.find0lement(By.link3e7t(93ourist 3rains9""8

     

    -ctions act 6 new -ctions(driver"8 ;;Create -ction obect for Driver

    act.conte7tClick(parentenu".build(".perform("8 ;;Conte7t Click

    act.sendKeys(Keys.-&&WL&4$,3".build(".perform("8

    3hread.sleep(1HHH"8

    act.sendKeys(Keys.-&&WLDW)".build(".perform("8

    3hread.sleep(1HHH"8

    act.sendKeys(Keys.0)30&".build(".perform("8

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

     

    1-. @! S'6">$ example

    We can use ava script command to perform actions.

    We can write code to fill up the te7t bo7 through ava script.

    +lease follow the steps mentioned below.

    1. Create Driver for any Browser(o!illa".

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    18/25

    #. $o to the %&'.

    . Create Nava Script e7ecutor obect for the Driver.

    *. Store the Nava Script command in a String Gariable.

    2. Nava Script 07ecutor obect e7ecutes the command in the Gariable.

    Navascript07ecutor s 6 (Navascript07ecutor" driver8

    String sCmd 6 9document.get0lementsBy)ame(?city?"[email protected]?ban?98

     s.e7ecuteScript(sCmd"8

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    12. *ultiple Elements

    We can count the number of links present in the page. We can also print the link te7t of each Web

    link.

    +lease follow the steps mentioned below.

    1. Create Driver for any Browser(o!illa".

    #. $o to the %&'.

    . /etch elements with tag ;;a in the entire page< store it in a 'ist.

    *. $et the count of 'inks present in the +age.

    2. 'oop through the links and print the -ttributes

    'ist all'inks6 driver.find0lements(By.7path(9;;a9""8

     ;;display the count of links in the page

    System.out.println(all'inks.si!e(""8

     ;;display the te7t for each link on the page

    for(int i6H8i

      ;;display href for each link

     System.out.println(all'inks.get(i".get-ttribute(9href9""8

     ;;display te7t for each link

      System.out.println(all'inks.get(i".get3e7t(""8

     ;;perform click action

     all'inks.get(i".click("8

    E

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    13. %ther Browser ("nternet Explorer&

    %sing 4nternet 07plorer with Web Driver.

    +lease follow the steps mentioned below.

    1. Set System +roperty for the Driver and give path of the 40 Driver.

    #. Create an Web Driver bect.

    . pen an %&'

    System.set+roperty(9webdriver.ie.driver9< 9D:OOselOObrowserdriversOO40DriverServer.e7e9"8

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    19/25

    WebDriver driver 6new 4nternet07plorerDriver("8

    driver.get(9www.google.com9"8

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    15. %ther Browser ('hrome&

    %sing Chrome with Web Driver.

    +lease follow the steps mentioned below.

    1. Set System +roperty for the Driver and give path of the Chrome Driver.

    #. Create an Web Driver bect.

    . pen an %&'

    System.set+roperty(9webdriver.chrome.driver9< 9D:OOselOObrowserdriversOOChromedriver.e7e9"8

    WebDriver driver 6 new ChromeDriver("8

    driver.get(9www.google.com9"8

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    18. >6%/A settin+s.

    +lease follow the steps mentioned below.

    1. 4mport Selenium.+ro7y

    #. Create a +rofile obect for /irefo7

    . Create a string variable with value.

    *. Create a +ro7y obect.

    2. Set the values through pro7y.

    5. Set the pro7y preference to pro7y obect using profile obect.

    A. +ass the profile obect to /irefo7 Driver.

    import org.opena.Selenium.+ro7y

    /irefo7+rofile profile 6 new /irefo7+rofile("8

    String +&FP 6 977.77.77.77:7798

    +ro7y pro7y 6 new +ro7y("8

    pro7y.,ttp+ro7y6+&FP8

    pro7y./tp+ro7y6+&FP8

    pro7y.Ssl+ro7y6+&FP8

    profile.Set+ro7y+references(pro7y"8

    /irefo7Driver driver 6 new /irefo7Driver(profile"8

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    1:. >a+e %nload authentication

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    20/25

    Sometimes when you are -utomating Web pages< you may come across +age onload

    -uthentication window. 3his window is not ava popup;div. 4t is windows popup. Selenium directly

    cannot handle this windows popup.

    ,ence we use -utoit sowftware tool. 3hrough Selenium we can handle this situation using -utoit.

    +lease follow the steps mentioned below.

    1.Download -utoit from the following %&l

      ( http:;;www.autoitscript.com;site;autoit;downloads; "

    #.4nstall downloaded software.

    . pen Script 0ditor

      Start6Q+rogram/iles6Q-uto4t 6QSci30 Script 0ditor.

    *.pen bect 4dentifier.

      Start6Q+rogram/iles6Q-uto4t 6Q-uto4t Window 4nfo.

    2.Drag and Drop finder tool in -uto4t Window 4nfo< to the Window you need to identify.

    5.Collect the 3itle )ame of window from (-uto4t Window 4nfo."

    A.Write the Script in the 0ditor.

    ++++++++++++++++++++++++++++++++++++++++++++++++++++0>?, =?DE+++++++++++++++++++++++++++++++++++++++++++++++++++++

    WinWait-ctive(9-uthentication &euired9"

    Send(9admin9"

    Send(93-BE admin3-BE 0)30&E9"

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    .Save the file as default save.(-uthentication1.e7e"

    R.&%);Compile the SC&4+3< it creates an e7e.

    1H.ention the e7e path in the +rogram before creation of Driver.

    E@0A8E#

    8rocess 8 Buntime.getBuntime().exec("D#CCavaprCCSEE:,>A WE&DB,1EBCC0>?,CC0uthenticationF.exe");

    WebDriver driver new !irefoxDriver();

    driver.get("http#$$FG-.FH7.F.F");

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    =;. File Download

    +lease follow the steps mentioned below.

    1. Create a +&/4'0 obect of Browser.

    #. Set +reference< by giving Download destination Directory.

    . Set +reference< by giving Default /older. H 6Q Desktop< 16QSystem Default 'ocation< # 6Q

    4ndicates a custom /older 'ocation

    *. Set +reference< - commaJseparated list of 40 types to save to disk without asking what to

    use to open the file. Default value is an empty string.

    -fter coding the above mentioned steps< now start the driver and click on Download button;link.

    1. Create Driver for any Browser(o!illa".

    #. $o to the %&'.

    . /etch the Download web element and click.

    /irefo7+rofile +rof 6 new /irefo7+rofile("8

    +rof.set+reference(9browser.download.dir9< 9D:OOava pr9"8

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    21/25

    +rof.set+reference(9browser.download.folder'ist9< #"8

    +rof.set+reference(9browser.helper-pps.never-sk.save3oDisk9name6?clientJdrivers?@;table;tbody;tr=1@;td=*@;a9"".click("8

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    =1. File pload

    +lease follow the steps mentioned below.

    1. Create Driver for any Browser(o!illa".

    #. $o to the %&'.

    . Store the Source path of file in a variable.

    *. /etch the %pload web element te7t bo7 and give path using variable.

    2. /etch the upload button and click

    WebDriver driver 6 new /irefo7Driver("8

    driver.get(9http:;;www.#shared.com;9"8

    String /ile+ath 6 9C:OO%sersOOabcOODesktopOOtest.7ml98

    driver.find0lement(By.id(9up/ield9"".sendKeys(/ile+ath"8

    driver.find0lement(By.7path(9;;input=>type6?image?@9"".click("8

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    ==. 7andlin+ @! ,E6$

    Sometimes you may get alerts as anticipated(through 4nsert;update;delete operation in database".

    3hese may be N-G- alerts.

    +lease follow the steps mentioned below to handle -lerts.

    1. Create Driver for any Browser(o!illa".

    #. $o to the %&'.

    . Pou get an alert asking to click on ?P0S? or ?)? button.

    *. /irst Confirm if it is N-G- alert window.

    2. Write a code to switch the control to -lert window.

    5. 4n the -lert window< either -CC0+3 by clicking on ?P0S?

      or C-)C0' by clicking on ?)?.

    WebDriver driver 6 new /irefo7Driver("8

    driver.get(9http:;;www.#shared.com;9"8

    driver.manage(".timeouts(".implicitlyWait(

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    22/25

    i'!ort org.o!enPa.seleni/'.y;i'!ort org.o!enPa.seleni/'.WebDriver;i'!ort org.o!enPa.seleni/'.refox.FirefoxDriver;i'!ort org.testng.annotations.After9lass;i'!ort org.testng.annotations.efore9lass;i'!ort org.testng.annotations.est;

     !/blic class Driver Q!rivate WebDriver driver; ?efore9lass !/blic void tart/!()Q  driver = new FirefoxDriver(); R ?est (descri!tion="Koogle ,ogin") !/blic void Koogle,ogin() trows -xce!tionQ  driver.get("tt!##www.g'ail.co'");  assert-P/als("ign in"8 driver.nd-le'ent(y.id("signn")).getAttrib/te("val/e"));  driver.nd-le'ent(y.id("-'ail")).send5eys("TTTTTTTTT");  driver.nd-le'ent(y.id("

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    23/25

    I :ode+set

    @8ath 'pe # !unctions

    :ode set # last()J position()J count()J id()J local+name()J namespace+uri()J name()String # string()J concat()J starts+with()J contains()J substring+before()J substring+after()J substring()J string+

    length()J normaliKe+space()J translate()

    &oolean # boolean()J not()J true()J false()J lang()

    :umber # number()J sum()J floor()J ceiling()J round()

    , will show 'ou how we can use some of these above functions in xpath to identif' the obects.

    :ode Set # last(),n the above html file there are six checkboxes and all are having same attributes (same t'pe and name)9ow we can select the last checkbox based on the position. We can use last() function to indentif' the lastobect among all similar obects.&elow code will check or uncheck the last checkbox.

    selenium.click("xpath($$input23t'pe4checkbox45)2last()5");9ow we can select the second last checkbox and third last checkbox. We can use last()+ function toindentif' the last obect among all similar obects.&elow code will check or uncheck the second last checkbox and thrid last checkbox respectivel'.selenium.click("xpath($$input23t'pe4submit45)2last()+F5");selenium.click("xpath($$input23t'pe4submit45)2last()+-5");

    :ode Set # position(),f 'ou want to select an' obect based on their position using xpath then 'ou can use position() function inxpath./ou want to select second checkbox and forth checkbox then use below commandselenium.click("xpath($$input23t'pe4checkbox45)2position()-5");selenium.click("xpath($$input23t'pe4checkbox45)2position()L5");above code will select second and forth checkbox respectivel'.

    String # starts+with()Aan' web sites create d'namic element on their web pages where ,ds of the elements gets generatedd'namicall'.Each time id gets generated differentl'. So to handle this situation we use some MavaScript functions.@8ath# $$button2starts+with(3idJ 4continue+4)5Sometimes an element gets identfied b' a value that could be surrounded b' other textJ then containsfunction can be used.o demonstrateJ the element can be located based on the NsuggestO class without havingto couple it with the NtopO and NbusinessO classes using the following

    @8ath# $$input2contains(3classJ 4suggest4)5.

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    24/25

    +/n te b/ild.x'l as Ant /ild

    +efres te !roEect and o!en te +e!orts folder

    Fro' te +e!orts folder8 o!en te index.t'l le wit Web rowserQ! Fow can I change the &rowser to &e used for running the test scriptsPA. Following are te ste!s

    Ko to te cong folder

    :!en te Vg/iUa/to'ation.!ro!erties le *nco''ent te needed browser cong/ration and co''ent te not needed

    browser in tis le and save te leQ! $oes 5e&$river support #le uploadsPA. Oes8 it is !ossible if yo/ call Web-le'entXsend5eys("#!at#to#le") on a le /!loadele'ent. 6a0e s/re yo/ don@t /se Web-le'entXclic0() on te le /!load ele'ent or tebrowser will ang.Q! 5hat input #elds have &een targeted in v, of the framework usingparameteriationA. ext boxes8 radio b/ttons8 dro! downs8 cec0 boxes8 a/to$s/ggest searc dro! down8and le /!load.Q! Fow can I handle multiple windowsP

    A. Oo/ can andle '/lti!le windows /sing te "WebDriver.switco().window()" 'etod $ere window na'e is reP/ired. f te na'e is not 0nown8 yo/ can /se"WebDriver.getWindowLandles()" to obtain a list of 0nown windows and ten switc to as!ecic window.Q! /an I make we&driver to wait for some event on defaultPA. Oes.-xa'!le newWebDriverWait(driver82%)./ntil(-x!ected9onditions.!resence:f-le'ent,ocated(y.id("loginox")))Q! $oes the framework support the !xlsx extension #les for parameteriationPA. Oes. We ave !rovided s/!!ort for .xlsx extension les i.e. 2%%$2%1% for'at8 /singA!ace

  • 8/16/2019 Top 20 Useful Commands in Selenium Webdriver

    25/25

    Q! Fow to 'aximie the &rowser to screen siePA. o 'axi'iHe te browser window to screen siHe ool0it.getcreeniHe() 'etod is/sed ool0it tool0it = ool0it.getDefaultToolkit ();Di'ension screen+esol/tion = new Di'ension((int)tool0it.getcreeniHe().getWidt()8 (int)

    tool0it.getcreeniHe().getLeigt());driver.'anage().window().setiHe(screen+esol/tion);Q! Fow to handle pageload time in we&driverPA. Oo/ can set te


Recommended