Selenium WebDriver Practical Guide - .

Transcription

#\IAMCommunityExperienceDistilledSelenium WebDriverPractical GuideInteractively automate web applications using Selenium WebDriverSatya AvasaralaPACKTPUBLISHINGwww.allitebooks.com1I open sourceÿcommunity experience cTistHied

Selenium WebDriverPractical GuideInteractively automate web applications usingSelenium WebDriverSatya Avasarala1I open sourcefIcommunity experience distilledPUBLISHINGBIRMINGHAM - MUMBAIwww.allitebooks.com

Selenium WebDriver Practical GuideCopyright 2014 Packt PublishingAll rights reserved. No part of this book may be reproduced, stored in a retrievalsystem, or transmitted in any form or by any means, without the prior writtenpermission of the publisher, except in the case of brief quotations embedded incritical articles or reviews.Every effort has been made in the preparation of this book to ensure the accuracyof the information presented. However, the information contained in this book issold without warranty, either express or implied. Neither the author, nor PacktPublishing, and its dealers and distributors will be held liable for any damagescaused or alleged to be caused directly or indirectly by this book.Packt Publishing has endeavored to provide trademark information about all of thecompanies and products mentioned in this book by the appropriate use of capitals.However, Packt Publishing cannot guarantee the accuracy of this information.First published: January 2014Production Reference: 1170114Published by Packt Publishing Ltd.Livery Place35 Livery StreetBirmingham B3 2PB, UK.ISBN 978-1-78216-885-0www.packtpub.comCover Image by Prashant Timappa Shetty com

CreditsAuthorProject CoordinatorSatya AvasaralaAmey SawantReviewersProofreaderAnuj ChaudharyClyde JenkinsDavid Askirk FotelIndexersDaniel LamHemangini BariRipon Al WasimMonica Ajmera MehtaAcquisition EditorsAnthony AlbuquerqueRekha NairPriya SubramaniRichard HarveyGraphicsLead Technical EditorPriya SinghYuvraj MannariAbhinash SahuTechnical EditorsProduction CoordinatorDennis JohnAparna BhagatVenu ManthenaGaurav ThingalayaCover WorkAparna BhagatCopy EditorsTanvi GaitondeKirti PaiAdithi Shettywww.allitebooks.com

About the AuthorSatya Avasarala has rich experience in Java development and automation testing.He is an engineer in computer science. He has used WebDriver for many yearsnow and has created several good automation frameworks. He has worked atvarious large software enterprises such as Oracle Corp, Yahoo! Inc., VMware Inc.,and the REA Group.In addition, he is also interested in Service Oriented Architectural design and%XVLQHVV ,QWHOOLJHQFH H LV DQ 2UDFOH FHUWLÀHG 6HUYLFH 2ULHQWHG UFKLWHFWXUH Infrastructure Implementation Expert and a Business Intelligence FoundationSuite Implementation Specialist.I would like to thank all my acquisition editors, technical editors,and project coordinators for constantly supporting me in completingthis book. I should also thank my colleagues, Pratik Patil and KerriRusnak, for their constant encouragement and support in writingthis book. Last but not least, I would like to thank my wife, Swathi9HQQHODJDQWL IRU VDFULÀFLQJ PDQ\ ZHHNHQGV ZKLOH , ZDV EXV\ writing this book. Without all these people, this book wouldn't havebeen a reality.www.allitebooks.com

About the ReviewersAnuj Chaudhary is a software engineer who enjoys working on software testingand automation. He has a vast experience with various testing methodologies suchas manual testing, automated testing, performance testing, and security testing. Hehas worked as an individual contributor and technical lead on various softwareprojects dealing with all of the stages in the application development life cycle.He has been awarded the title of Microsoft MVP twice in a row. He writes a blog thatyou can visit at www.anujchaudhary.com.I would like to thank and congratulate the Packt Publishing team forpublishing this awesome book.David Askirk Fotel has worked with computers since his parents broughthome an old, used IBM PS/2. He started his development career writing simpleprograms in QBasic and later in Pascal. From there, he moved on to writingprograms in C. Later on, he moved on to Java and other languages. His greatestexperience so far was with Lisp, which had a great impact on his programmingstyle and approach to code.David has worked on test-driven development and as a test manager, implementingSelenium tests on an e-learning system.7KLV ERRN LV WKH ÀUVW RQ ZKLFK 'DYLG KDV ZRUNHG EXW ZLOO QRW EH WKH ODVW www.allitebooks.com

Daniel Lam is an Agile Test Developer with experience in open and closed sourcetest tools. He specializes in Java, Selenium WebDriver, Continuous Integration, andBDD test frameworks.Ripon Al Wasim is a software engineer living in Dhaka, Bangladesh. He has 12years' experience in the software industry, three years in software development,and nine years in software testing (both manual and automated). He has also beeninvolved in conducting software testing courses in various companies. He hasworked for clients in various countries such as Japan, USA, Finland, Norway, andBangladesh.Ripon started participating in posting professional questions and answers on Stack2YHUÁRZ LQ WKH \HDU DW m.5LSRQ LV D 6XQ &HUWLÀHG -DYD 3URJUDPPHU 6&-3 H LV -DSDQHVH /DQJXDJH 3URÀFLHQF\ 7HVW -/37 /HYHO FHUWLÀHG DQG LV D OLWWOH IDPLOLDU ZLWK -DSDQHVH FXOWXUH DV KH VWD\HG LQ -DSDQ IRU RQH \HDU DV DQ ,7 SURIHVVLRQDO 7KLV ERRN LV 5LSRQ V ÀUVW RIÀFLDO HIIRUW I would like to thank my mother and wife for fostering a helpingand inspiring environment at home so I could study and review.I am also deeply thankful and grateful to Cefalo Amravi Ltd.(http://cefalo.com/en), my current company, for providing mea good opportunity to work with automated testing using SeleniumWebDriver. I would like to thank Yves Hwang, Product Managerat Varnish Software (https://www.varnish-software.com/) andPartha Guha Roy, CTO of Cefalo Amravi Ltd. for providing technicalassistance during my project work.www.allitebooks.com

www.PacktPub.com6XSSRUW ¿OHV H%RRNV GLVFRXQW RIIHUV DQG PRUHYou might want to visit www.PacktPub.com IRU VXSSRUW ÀOHV DQG GRZQORDGV UHODWHG to your book.Did you know that Packt offers eBook versions of every book published, with PDFDQG H3XE ÀOHV DYDLODEOH" RX FDQ XSJUDGH WR WKH H%RRN YHUVLRQ DW www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy.Get in touch with us at service@packtpub.com for more details.At www.PacktPub.com, you can also read a collection of free technical articles, signup for a range of free newsletters and receive exclusive discounts and offers on Packtbooks and eBooks.[TIPACKToTMhttp://PacktLib.PacktPub.com'R \RX QHHG LQVWDQW VROXWLRQV WR \RXU ,7 TXHVWLRQV" 3DFNW/LE LV 3DFNW V RQOLQH GLJLWDO book library. Here, you can access, read and search across Packt's entire libraryof books.Why Subscribe? Fully searchable across every book published by PacktCopy and paste, print and bookmark contentOn demand and accessible via web browserFree Access for Packt account holdersIf you have an account with Packt at www.PacktPub.com, you can use this to accessPacktLib today and view nine entirely free books. Simply use your login credentialsfor immediate access.www.allitebooks.com

www.allitebooks.com

Table of ContentsPrefaceChapter 1: ,QWURGXFLQJ :HE'ULYHU DQG :HE(OHPHQWV18QGHUVWDQGLQJ WKH KLVWRU\ RI 6HOHQLXPSelenium 1 or Selenium Remote Control or Selenium RCSelenium 2 or Selenium WebDriver or WebDriverDifferences between Selenium 1 and Selenium 291213Setting up a project in Eclipse:HE(OHPHQWVLocating WebElements using WebDriver15 21Handling the browserHaving better APIsTesting mobile appsHaving developer support and advanced functionalities7KH ¿QG(OHPHQW PHWKRG7KH ¿QG(OHPHQWV PHWKRGFirebugUsing the By locating mechanismActions on WebElements7KH JHW WWULEXWH PHWKRG7KH VHQG.H\V PHWKRG7KH FOHDU PHWKRG7KH VXEPLW PHWKRG7KH JHW&VV9DOXH PHWKRG7KH JHW/RFDWLRQ PHWKRG7KH JHW6L]H PHWKRG7KH JHW7H[W PHWKRG7KH JHW7DJ1DPH PHWKRG7KH LV'LVSOD\HG PHWKRG7KH LV(QDEOHG PHWKRG7KH LV6HOHFWHG PHWKRG14141414 222332 6XPPDU\ www.allitebooks.com

Table of Contents&KDSWHU ([SORULQJ GYDQFHG ,QWHUDFWLRQV RI :HE'ULYHU8QGHUVWDQGLQJ DFWLRQV EXLOG DQG SHUIRUP/HDUQLQJ PRXVH EDVHG LQWHUDFWLRQV7KH PRYH%\2IIVHW DFWLRQ7KH FOLFN DW FXUUHQW ORFDWLRQ DFWLRQThe click on a WebElement action7KH FOLFN QG ROG DW FXUUHQW ORFDWLRQ DFWLRQ7KH FOLFN QG ROG D :HE(OHPHQW DFWLRQ7KH UHOHDVH DW FXUUHQW ORFDWLRQ DFWLRQ7KH UHOHDVH RQ DQRWKHU :HE(OHPHQW DFWLRQ7KH PRYH7R(OHPHQW DFWLRQ7KH GUDJ QG'URS%\ DFWLRQ7KH GUDJ QG'URS DFWLRQ7KH GRXEOH&OLFN DW FXUUHQW ORFDWLRQ DFWLRQ7KH GRXEOH&OLFN RQ :HE(OHPHQW DFWLRQ7KH FRQWH[W&OLFN RQ :HE(OHPHQW DFWLRQ7KH FRQWH[W&OLFN DW FXUUHQW ORFDWLRQ DFWLRQ/HDUQLQJ NH\ERDUG EDVHG LQWHUDFWLRQV7KH NH\'RZQ DQG NH\8S DFWLRQV7KH VHQG.H\V PHWKRG6XPPDU\ 49 &KDSWHU ([SORULQJ WKH )HDWXUHV RI :HE'ULYHU &KDSWHU 'LIIHUHQW YDLODEOH :HE'ULYHUV 6HWWLQJ WKH GHVLUHG FDSDELOLWLHV IRU D EURZVHU7DNLQJ VFUHHQVKRWV/RFDWLQJ WDUJHW ZLQGRZV DQG L)UDPHV6ZLWFKLQJ DPRQJ ZLQGRZV6ZLWFKLQJ DPRQJ IUDPHV DQGOLQJ DOHUWV([SORULQJ 1DYLJDWH:DLWLQJ IRU :HE(OHPHQWV WR ORDG,PSOLFLW ZDLW WLPH([SOLFLW ZDLW WLPH DQGOLQJ FRRNLHV6XPPDU\)LUHIR['ULYHU8QGHUVWDQGLQJ WKH )LUHIR[ SUR¿OH GGLQJ WKH H[WHQVLRQ WR )LUHIR[6WRULQJ DQG UHWULHYLQJ D SUR¿OH 'HDOLQJ ZLWK )LUHIR[ SUHIHUHQFHV 6HWWLQJ SUHIHUHQFHVUnderstanding frozen preferences 91[ ii ]

Table of ContentsFirefox binary93Installing multiple versions of Firefox,QWHUQHW([SORUHU'ULYHU,QVWDOOLQJ ,QWHUQHW([SORUHU'ULYHU:ULWLQJ \RXU ¿UVW WHVW VFULSW IRU WKH ,( EURZVHU%XLOGLQJ WKH ,QWHUQHW([SORUHU GULYHU VHUYLFH8QGHUVWDQGLQJ ,('ULYHU FDSDELOLWLHV&KURPH'ULYHU,QVWDOOLQJ &KURPH'ULYHU:ULWLQJ \RXU ¿UVW WHVW VFULSW IRU WKH &KURPH EURZVHU8VLQJ &KURPH2SWLRQV6DIDUL'ULYHU:ULWLQJ \RXU ¿UVW WHVW VFULSW IRU WKH 6DIDUL EURZVHU2SHUD'ULYHU,QVWDOOLQJ 2SHUD'ULYHU:ULWLQJ \RXU ¿UVW WHVW VFULSW IRU WKH 2SHUD EURZVHU6XPPDU\Chapter 5: 8QGHUVWDQGLQJ :HE'ULYHU (YHQWV,QWURGXFLQJ (YHQW)LULQJ:HE'ULYHU DQG (YHQW/LVWHQHU FODVVHV&UHDWLQJ DQ LQVWDQFH RI (YHQW/LVWHQHU,PSOHPHQWLQJ :HE'ULYHU(YHQW/LVWHQHU([WHQGLQJ EVWUDFW:HE'ULYHU(YHQW/LVWHQHU&UHDWLQJ D :HE'ULYHU LQVWDQFH&UHDWLQJ (YHQW)LULQJ:HE'ULYHU DQG (YHQW/LVWHQHU LQVWDQFHV5HJLVWHULQJ (YHQW/LVWHQHU ZLWK (YHQW)LULQJ:HE'ULYHUExecuting and verifying the events5HJLVWHULQJ PXOWLSOH (YHQW/LVWHQHUV([SORULQJ GLIIHUHQW :HE'ULYHU HYHQW OLVWHQHUVListening for WebElement value changeListening for WebElement clickedListening for a WebElement search eventListening for browser back navigationListening for browser forward navigationListening for browser navigateTo eventsListening for script executionListening for any exceptionUnregistering EventListener with EventFiringWebDriver6XPPDU\[ iii ]93 119 121122122122123123123124124

Table of Contents&KDSWHU 'HDOLQJ ZLWK , 2/HDUQLQJ DERXW WKH )LOH DQGOHU FODVV&RS\LQJ ¿OHV IURP WKH VRXUFH WR WKH GHVWLQDWLRQ GLUHFWRU\&RS\LQJ ¿OHV IURP WKH VRXUFH WR WKH GHVWLQDWLRQ GLUHFWRU\ EDVHG RQ ¿OHQDPH VXI¿[&UHDWLQJ D GLUHFWRU\'HOHWLQJ D ¿OH RU GLUHFWRU\8QGHUVWDQGLQJ WKH ,V LSSHG PHWKRG8QGHUVWDQGLQJ WKH PDNH([HFXWDEOH PHWKRG8QGHUVWDQGLQJ WKH PDNH:ULWDEOH PHWKRG5HDGLQJ D ¿OH8QGHUVWDQGLQJ WKH FDQ([HFXWH PHWKRG/HDUQLQJ DERXW WKH 7HPSRUDU\)LOHV\VWHP FODVV8QGHUVWDQGLQJ WKH GHIDXOW WHPSRUDU\ ¿OHV\VWHPCreating a directory in DefaultTmpFSDeleting a temporary directory'HOHWLQJ PXOWLSOH ¿OHV&KDQJLQJ WKH WHPSRUDU\ ¿OHV\VWHP/HDUQLQJ DERXW WKH LS FODVV&RPSUHVVLQJ D GLUHFWRU\'HFRPSUHVVLQJ D GLUHFWRU\6XPPDU\&KDSWHU ([SORULQJ 5HPRWH:HE'ULYHU DQG :HE'ULYHU%DFNHG6HOHQLXP,QWURGXFLQJ 5HPRWH:HE'ULYHUUnderstanding the RemoteWebDriver serverDownloading the serverRunning the serverUnderstanding the RemoteWebDriver clientConverting an existing test script to use RemoteWebDriver server8VLQJ 5HPRWH:HE'ULYHU IRU WKH )LUHIR[ EURZVHUUsing RemoteWebDriver and the IE browser8VLQJ 5HPRWH:HE'ULYHU DQG WKH &KURPH EURZVHU([WHQGLQJ WKH 5HPRWH:HE'ULYHU FOLHQW WR WDNH VFUHHQVKRWV8QGHUVWDQGLQJ WKH -621 ZLUH SURWRFRO5HSODFLQJ WKH FOLHQW OLEUDU\ ZLWK \RXU RZQ FRGH([SORULQJ :HE'ULYHU%DFNHG6HOHQLXP6XPPDU\[ iv ] 133134 141141141143143 149

Table of Contents&KDSWHU 8QGHUVWDQGLQJ 6HOHQLXP *ULG([SORULQJ 6HOHQLXP *ULG8QGHUVWDQGLQJ WKH KXE8QGHUVWDQGLQJ WKH QRGH0RGLI\LQJ WKH H[LVWLQJ WHVW VFULSW WR XVH 6HOHQLXP *ULG5HTXHVWLQJ IRU QRQUHJLVWHUHG FDSDELOLWLHV4XHXLQJ XS WKH UHTXHVW LI WKH QRGH LV EXV\'HDOLQJ ZLWK WZR QRGHV ZLWK PDWFKLQJ FDSDELOLWLHV&RQ¿JXULQJ 6HOHQLXP *ULG6SHFLI\LQJ QRGH FRQ¿JXUDWLRQ SDUDPHWHUV6HWWLQJ VXSSRUWHG EURZVHUV E\ D QRGH6HWWLQJ QRGH WLPHRXWV6HWWLQJ WKH OLPLW RQ EURZVHU LQVWDQFHV5HUHJLVWHULQJ WKH QRGH DXWRPDWLFDOO\6HWWLQJ QRGH KHDOWK FKHFN WLPH8QUHJLVWHULQJ DQ XQDYDLODEOH QRGH6HWWLQJ WKH EURZVHU WLPHRXW XE FRQ¿JXUDWLRQ SDUDPHWHUV :DLWLQJ IRU D PDWFK RI GHVLUHG FDSDELOLW\&XVWRPL]HG &DSDELOLW\0DWFKHU:DLW7LPHRXW IRU D QHZ VHVVLRQ'LIIHUHQW ZD\V WR VSHFLI\ WKH FRQ¿JXUDWLRQ6XPPDU\&KDSWHU 8QGHUVWDQGLQJ 3DJH2EMHFW 3DWWHUQ&UHDWLQJ WHVW FDVHV IRU RXU :RUG3UHVV EORJTest case 1 – Adding a new post to our WordPress blogTest case 2 – Deleting a post from our WordPress blogTest case 3 – Counting the number of posts on our WordPress blog:KDW LV WKH 3DJH2EMHFW SDWWHUQ"8VLQJ WKH #)LQG%\ DQQRWDWLRQ8QGHUVWDQGLQJ 3DJH)DFWRU\*RRG SUDFWLFHV IRU WKH 3DJH2EMHFWV GHVLJQConsider a web page as a services provider OZD\V ORRN IRU LPSOLHG VHUYLFHV8VLQJ 3DJH2EMHFWV ZLWKLQ D 3DJH2EMHFW7KH GG1HZ3RVW 3DJH2EMHFW7KH OO3RVWV3DJH 3DJH2EMHFW&RQVLGHU PHWKRGV LQ 3DJH2EMHFWV DV VHUYLFHV DQG QRW DV 8VHU FWLRQV,GHQWLI\LQJ VRPH :HE(OHPHQWV RQ WKH À\.HHSLQJ WKH SDJH VSHFL¿F GHWDLOV RII WKH WHVW VFULSW8QGHUVWDQGLQJ ORDGDEOH FRPSRQHQWV[v] 192193194 199

Table of Contents:RUNLQJ RQ DQ HQG WR HQG H[DPSOH RI :RUG3UHVV/RRNLQJ DW DOO WKH 3DJH2EMHFWV7KH GPLQ/RJLQ3DJH 3DJH2EMHFW7KH OO3RVWV3DJH 3DJH2EMHFWThe AddNewPostPage PageObjectThe EditPostPage PageObjectThe DeletePostPage PageObject/RRNLQJ DW WKH WHVW FDVHV 213213214 GGLQJ D QHZ SRVW(GLWLQJ D SRVW'HOHWLQJ D SRVW&RXQWLQJ SRVWV 6XPPDU\&KDSWHU 7HVWLQJ L26 DQG QGURLG SSV'LIIHUHQW IRUPV RI PRELOH DSSOLFDWLRQV YDLODEOH VRIWZDUH WRROV XWRPDWLQJ L26 DQG QGURLG WHVWV XVLQJ SSLXPAutomating iOS application tests XWRPDWLQJ QGURLG DSSOLFDWLRQ WHVWV3UHUHTXLVLWHV IRU SSLXP6HWWLQJ XS ;FRGH6HWWLQJ XS QGURLG 6'.Installing AppiumAutomating for iOS XWRPDWLQJ IRU QGURLG6XPPDU\ 224 231232 ,QGH[ [ vi ]

PrefaceThis book is about Selenium WebDriver, also known as Selenium 2, which is a UIautomation tool used by software developers and QA engineers to test their webapplication on different web browsers. The reader is expected to have a basic ideaof programming, preferably using Java, because we take the reader through severalfeatures of WebDriver using code examples. This book can be used as a reference foryour day-to-day usage of WebDriver.What this book coversChapter 1, Introducing WebDriver and WebElements ZLOO VWDUW RII E\ EULHÁ\ GLVFXVVLQJ the history of Selenium and the differences between Selenium 1 and Selenium 2.Then, we quickly jump into WebDriver by describing how it perceives a web page.We will also look at what a WebDriver's WebElement is. Then, we talk about locatingWebElements on a web page and performing some basic actions on them.Chapter 2, Exploring Advanced Interactions of WebDriver, will dive deeply into moreadvanced actions that WebDriver can perform on the WebElements of a web page,such as the dragging-and-dropping of elements from one frame of a page to anotherDQG ULJKW FRQWH[W FOLFNLQJ RQ :HE(OHPHQWV :H UH VXUH \RX ZLOO ÀQG WKLV FKDSWHU interesting to read.Chapter 3, Exploring the Features of WebDriver, will talk about some advanced featuresof WebDriver, such as taking screenshots of web pages, executing JavaScript, andhandling cookies and proxies.

PrefaceChapter 4, Different Available WebDrivers, will talk about various implementations ofWebDriver, such as FirefoxDriver, IEDriver, and ChromeDriver. When we discussWebDriver in Chapter 1, Introducing WebDriver and WebElements, we will see that:HE'ULYHU KDV VSHFLÀF LPSOHPHQWDWLRQV IRU PRVW RI WKH SRSXODU EURZVHUV DYDLODEOH on the market.Chapter 5, Understanding WebDriver Events, will deal with the event-handling aspectof WebDriver. To state a few, events can be a value change on a WebElement,a browser back-navigation invocation, script execution completion, and so on.Chapter 6, Dealing with I/O ZLOO LQWURGXFH \RX WR WKH ÀOH KDQGOLQJ IHDWXUHV RI :HE'ULYHU &RQFHSWV VXFK DV FRS\LQJ ÀOHV XSORDGLQJ ÀOHV DQG GHOHWLQJ ÀOHV ZLOO be discussed in this chapter.Chapter 7, Exploring RemoteWebDriver and WebDriverBackedSelenium, willdeal with two very important topics of WebDriver: RemoteWebDriver andWebDriverBackedSelenium. If you want to execute a WebDriver installed on adifferent machine from your machine, you can use the RemoteWebDriver classto handle all your commands for that remote machine. One of its popular use casesis browser compatibility testing. The other class we talk about in this chapter isWebDriverBackedSelenium. This is useful for people who want to use WebDriver,but still have many of their existing tests using Selenium 1. Finally, we will migratesome code using Selenium1 APIs to use WebDriver APIs.Chapter 8, Understanding Selenium Grid, will talk about one important and interestingfeature of Selenium named Selenium Grid. Using this, you can submit yourdeveloped automation scenarios to a server and specify there the target platform,that is, the OS, browser type, and version, upon which you want these scenariosWR EH H[HFXWHG ,I D QRGH ZLWK VXFK D FRQÀJXUDWLRQ LV UHJLVWHUHG DQG DYDLODEOH WKH server will dispatch your job to that node, and it will take care of executing yourautomation scenarios in its environment and publish the results back to the server.Chapter 9, Understanding PageObject Pattern, will talk about a well-known designpattern named the PageObject pattern. This is a proven pattern that will give youa better handle on your automation framework and scenarios.Chapter 10, Testing iOS and Android Apps, we will take you through how WebDrivercan be used to automate your test scripts for iOS and Android applications. We willalso discuss a recently developed software tool called Appium.By the end of this book, we are sure you will be one of the world's advancedWebDriver users.[ ]

PrefaceWhat you need for this bookThe following sections describe the installation of components required to work withthe code in this book.Installing JavaIn this book, all the code examples that we show covering various features ofWebDriver will be in Java. To follow these examples and write your own code, youneed Java Development Kit installed on your computer. The latest version of JDKcan be downloaded from the following /install/windows/jdkinstallation-windows.htmlA step-by-step installation guide is available at the following lling EclipseThis book is a practical guide that expects the user to write and execute WebDriverexamples. For this, it would be handy to install a Java IDE. You can install yourfavorite IDE. Here, I am installing Eclipse. It can be downloaded from thefollowing ipse-ide-javadevelopers/junosr2Installing FirefoxMost of the work in this book will be done using Firefox. However, we do talkabout other browsers and their respective drivers in Chapter 4, Different AvailableWebDrivers. We will work with Firefox 17.0.1, which has been tested and triedagainst WebDriver 2.33.0. It can be downloaded from the following ox/releases/17.0.1/Installing FirebugFirebug is one of the add-ons of Firefox. It is widely used to inspect HTML elementson a web page. You can get Firebug from the following link:https://getfirebug.com/[ ]

Preface IWHU LQVWDOODWLRQ ZKHQ \RX RSHQ WKH )LUHIR[ EURZVHU \RX VKRXOG VHH WKH ÀUHEXJ icon on the top-right corner of the browser, as shown highlighted in red in thefollowing screenshot:Firefox41 'Mozilla Firefox Start Page Go too WebsiteCEPfirebug# Emozillay\Google 1 1aSearchFast. Smart. Safe. It's never been easier to put Firefox on your Androidphone.4DownloadsBookmarks ft-HistoryAdd-onsoSyncSettingsNow, click on the Firebug icon to load the Firebug UI, as shown in the followingscreenshot:a Mozilla Firefox Start Page f* & Go to a Website'Cp' firebugc-ft- -mozilla Goggle0 bodyEditConsoleHTML" CSSScripthtmlDOMphone.* *QnumlAailf- SearchFast. Smart. Safe. It's never been easier to put Firefox on your AndroidNetfiAnkmaikt. ftWirtnniJWMÿnr.vCm,Style !DOCTYPS haal Computedbody {H html xmlns ”http://www-w3.org/1999/xhtml" 5 head LayoutDOMaboutHome.css (line 10)*-muz -box-orient: vertical; body dir ”ltr " backgroundimage: url ( "chrome ://brc div cla33 ”spacer " /div 15OftCookies div id ”topSection” /content/abouthome div class "spacer" /div /noise .png”) , lineargradient (rgba 255, 255,5 div id ”launcher" a id "aboutMozilla" href "http: //www.mozilla. org/about/"x/a 255, 0.7), rgba (255,255, 255, 0.4));display: -moz-box; /bcdy /html height: 100%;margin: 0;width: 100%;x[ ]v

PrefaceInstalling FirePathAfter you have installed the Firebug add-on to Firefox, it's time to extend Firebugto have something named FirePath. FirePath is used to get XPath and CSS valuesof an HTML element on a web page. You can download FirePath from thefollowing addon/FirePath/After installation, you should see a new tab in the Firebug UI for FirePath, as shownin the following screenshot: El Google c if* Googlegoogle.com.auGet to Google faster. Add Google to your start screen.SearchImagesMapsPlayYouTubePNo aliaL&s 'ConsoleTop Window HighlightHTMLXPath:CSSScriptDOMNetCookiesFirePath .//*[@id 'gs ttiO']Q div id ”gbfwa" class "gbqfwa '* EJ div id "gbqfqw" class ''gbqfqw gsfe a" B div id "gbqfqwb" clas3 "gbqfqwc" B table id ”gs idO'' class '’gstl 0B tbody B tr lst-t" cellspacing ''0'' cellpadding "0" style "height: 27px; padding: Opx; " td id "g3 ttcQ '* 3tyle "white-3pace : nowrap;" dir "lbr"/ td id ''g3 ttiO" cla33 "g3ib an II td cXas3 ''gsib b" /tr /cbody /table /div /div /div 1 matching node[5sIDownloading WebDriver client library(language bindings)As discussed earlier, test scripts need a client library with which to interact, orFRPPDQG :HE'ULYHU WR H[HFXWH VSHFLÀF XVHU HYHQWV DJDLQVW D ZHE DSSOLFDWLRQ being tested on a browser. For this, you need to download the WebDriver clientlibrary. In this book, we use Java language bindings to create and execute ourautomation scripts.[5]

PrefaceAt the time of writing this book, all the code examples are written based on SeleniumJava Version 2.33.0. It is recommended that you download that version from thefollowing ads/detail?name seleniumjava-2.33.0.zip&can 2&q Downloading the Firefox DriverThe good news is that you have already downloaded the Firefox Driver. Yes, theFirefox Driver comes along with client libraries. But, for other drivers, such as theIE Driver, Safari Driver, Chrome Driver, and so on, you have to download themexplicitly from the following link:http://docs.seleniumhq.org/download/We will download them when we need to in Chapter 4, Different Available WebDrivers.Who this book is forIf you are a quality assurance/testing professional, software developer, or webapplication developer looking to create automation test scripts for your webapplications, this is the perfect guide for you! As a prerequisite, this book expectsyou to have a basic understanding of Java programming, although any previousknowledge of WebDriver or Selenium 1 is not needed. By the end of this book, youwill have acquired a comprehensive knowledge of WebDriver, which will help youin writing your automation tests.Conventions,Q WKLV ERRN \RX ZLOO ÀQG D QXPEHU RI VW\OHV RI WH[W WKDW GLVWLQJXLVK DPRQJ GLIIHUHQW kinds of information. Here are some examples of these styles, and an explanation oftheir meaning.&RGH ZRUGV LQ WH[W GDWDEDVH WDEOH QDPHV IROGHU QDPHV ÀOHQDPHV ÀOH H[WHQVLRQV pathnames, dummy URLs, user input, and Twitter handles are shown as follows:"The moveByOffset() method is used to move the mouse from its current positionto another point on the web page."A block of code is set as follows:public class NavigateToAUrl {public static void main(String[] args){WebDriver driver new FirefoxDriver();[ ]

Prefacedriver.get("http://www.google.com");}}When we wish to draw your attention to a particular part of a code block, therelevant lines or items are set in bold:public class GoogleSearchButtonByName {public static void main(String[] args){WebDriver driver new );WebElement searchBox it();}}Any command-line input or output is written as follows:java -jar selenium-server-standalone-2.33.0.jar -role node -hubhttp://172.16.87.131:1111/grid/register -registerCycle 10000New terms and important words are shown in bold. Words that you see on thescreen, in menus or dialog boxes for example, appear in the text like this: "OpenEclipse from the directory you have installed it in earlier. Navigate to File New Java Project".Warnings or important notes appear in a box like this.Tips and tricks appear like this.11Reader feedbackFeedback from our readers is always welcome. Let us know what you think aboutthis book—what you liked or may have disliked. Reader feedback is important for usto develop titles that you really get the most out of.To send us general feedback, simply send an e-mail to feedback@packtpub.com,and mention the book title via the subject of your message.If there is a topic that you have expertise in and you are interested in either writingor contributing to a book, see our author guide on www.packtpub.com/authors.[ ]

Preface&XVWRPHU VXSSRUWNow that you are the proud owner of a Packt book, we have a number of thingsto help you to get the most from your purchase.'RZQORDGLQJ WKH H[DPSOH FRGH RX FDQ GRZQORDG WKH H[DPSOH FRGH ÀOHV IRU DOO 3DFNW ERRNV \RX KDYH SXUFKDVHG from your account at http://www.packtpub.com. If you purchased this bookelsewhere, you can visit http://www.packtpub.com/support and register to haveWKH ÀOHV H PDLOHG GLUHFWO\ WR \RX ErrataAlthough we have taken every care to ensure the accuracy of our content, mistakesGR KDSSHQ ,I \RX ÀQG D PLVWDNH LQ RQH RI RXU ERRNV³PD\EH D PLVWDNH LQ WKH WH[W RU the code—we would be grateful if you would report this to us. By doing so, you cansave other readers from frustration and help us improve subsequent versions of thisERRN ,I \RX ÀQG DQ\ HUUDWD SOHDVH UHSRUW WKHP E\ YLVLWLQJ http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link,DQG HQWHULQJ WKH GHWDLOV RI \RXU HUUDWD 2QFH \RXU HUUDWD DUH YHULÀHG \RXU VXEPLVVLRQ will be accepted and the errata will be uploaded on our website, or added to any list ofexisting errata, under the Errata section of that title. Any existing errata can be viewedby selecting your title from http://www.packtpub.com/support.PiracyPiracy of copyright material on the Internet is an ongoing problem across all media.At Packt, we take the protection of our copyright and licenses very seriously. If youcome across any illegal copies of our works, in any form, on the Internet, pleaseprovide us with the location address or website name immediately so that we canpursue a remedy.Please contact us at copyright@packtpub.com with a link to the suspectedpirated material.We appreciate your help in protecting our authors, and our ability to bring youvaluable content.QuestionsYou can contact us at questions@packtpub.com if you are having a problem withany aspect of the book, and we will do our best to address it.[ ]

1Introducing WebDriver andWebElements,Q WKLV FKDSWHU ZH ZLOO ORRN EULHÁ\ LQWR WKH 6HOHQLXP KLVWRU\ DQG SURFHHG WR WKH basic components of a web page, WebElements. We will learn different ways tolocate WebElements on a web page and execute various user actions on them. Wewill cover the following topics in this chapter: History of Selenium Difference between Selenium 1 and Selenium 2 Setting up an Eclipse project to execute the example code Locating WebElements on a web page Actions that can be taken on the WebElements8QGHUVWDQGLQJ WKH KLVWRU\ RI 6HOHQLXPThough this book is not intended to deal with Selenium 1, it is a good idea to knowEULHÁ\ DERXW LW EHIRUH ZH VWDUW RII ZLWK :HE'ULYHU ,Q WKLV ZD\ ZH FDQ XQGHUVWDQG how and why WebDriver has evolved.6HOHQLXP RU 6HOHQLXP 5HPRWH &RQWURO RU 6HOHQLXP 5&Selenium RC is a popular UI automation library, allowing developers and testersto automate their interactions with a Web Application Under Test (WAUT) byproviding them with the necessary libraries, supported in multiple languages,to program.

Introducing WebDriver and WebElementsIn terms of design, Selenium RC chose to use generic JavaScript named SeleniumCore to drive the WAUT on a browser. However, the decision of using genericJavaScript that can drive the WAUT on any browser should comply with a securitypolicy named Same-Origin Policy. Every available browser in the market imposesthis policy on the websites that are loaded on it.To know about th

test tools. He specializes in Java, Selenium WebDriver, Continuous Integration, and BDD test frameworks. Ripon Al Wasim is a software engineer living in Dhaka, Bangladesh. He has 12 years' experience in the software industry, three years in software development, and nine years in softw