Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Selenium Testing Tools Cookbook Second Edition
Selenium Testing Tools Cookbook Second Edition

Selenium Testing Tools Cookbook Second Edition: Over 90 recipes to help you build and run automated tests for your web applications with Selenium WebDriver

eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Selenium Testing Tools Cookbook Second Edition

Chapter 2. Finding Elements

In this chapter, we will see how to use Selenium WebDriver API to find elements on a Web page and interact with these elements. We will explore various locator strategies supported by Selenium WebDriver. You will learn about:

  • Using browser tools for inspecting elements and page DOM
  • Finding an element using the findElement method
  • Finding elements using the findElements method
  • Finding links
  • Finding elements by tag name
  • Finding elements using CSS selectors
  • Finding elements using XPath
  • Finding elements using tag text contents
  • Finding elements using advanced CSS selectors
  • Using jQuery selectors

Introduction

Web applications, and the web pages within these applications, are commonly written in a mix of Hyper Text Markup Language (HTML), Cascading Style Sheets (CSS), and JavaScript code. Based on user actions like navigating to a website Uniform Resource Locator (URL) or clicking the submit button, a browser sends a request to a web server. Web server processes this request and sends back a response with HTML and related resources, such as JavaScript, CSS, Images, and so on, back to the Browser. The information received from a server is used by the browser to render a web page with various visual elements, such as textboxes, buttons, labels, tables, forms, checkboxes, radio boxes, lists, images, and so on, on the page. While doing so, the browser hides the HTML code and related resources from the user. The user is presented with a graphical user interface in the browser window.

When we want to automate browser interaction using Selenium, we need to tell Selenium how to find a particular...

Using browser tools for inspecting elements and page structure

Before we start exploring how to find elements on a page, we need to analyze the page to understand the Document Object Model (DOM) tree, what properties or attributes are defined for the elements displayed on the page, how JavaScript or AJAX calls are made from the application, and so on.

Browsers use the HTML code written for the page to render visual elements in the browser window. It uses other resources, including JavaScript, CSS, images, and so on, to decide the look, feel, and behavior of these elements.

Here is an example of a BMI Calculator application page and the HTML code written to render this page in a browser, as displayed in the following screenshot:

Using browser tools for inspecting elements and page structure

You can view the code written for a page by right-clicking in the browser window and selecting the View Page Source option from the pop-up menu. This will display the HTML code of the page in a separate window, as shown in the following screenshot:

Using browser tools for inspecting elements and page structure

We need tools that...

Finding an element using the findElement method

Finding elements in Selenium WebDriver is done by using the findElement() and findElements() methods provided by the WebDriver and WebElement interface.

The findElement() method returns an instance of a WebElement that is found in the page DOM based on specified locators, also called search criteria. If it does not find an element using the specified search criteria, it will throw the NoSuchElementFound exception.

The findElements() method returns a list of WebElements matching the search criteria. If no elements are found, it returns an empty list.

Find methods take a locator or a query object as an instance of a By class as an argument. Selenium WebDriver provides a By class to support various locator strategies. The following table lists various locator strategies supported by Selenium WebDriver:

Strategy

Syntax

Description

By ID

Java: driver.findElement(By.id(<element ID>))

C#: driver.FindElement(By.Id(<elementID>))

Python...

Finding elements using the findElements method

Selenium WebDriver provides the findElements() method, using which we can find more than one element matching the specified search criteria. This method is useful when we want to work with a group of similar elements. For example, we can get all the links displayed on a page, or get all rows from a table, and so on.

In this recipe, we will get all the links and print their targets by using the findElements() method.

How to do it...

Let's create a test that will get all the links from a page, verify the count of links, and print a target for each link, as follows:

@Test
public void testFindElements() {
    //Get all the links displayed on Page
    List<WebElement> links = driver.findElements(By.tagName("a"));

    //Verify there are four links displayed on the page
    assertEquals(4, links.size());

    //Iterate though the list of links and print
    //target for each link
    for(WebElement link : links) {
        System...

Finding links

Selenium WebDriver provides two special methods to find links on a page. Links can be searched either by their text or by partial text.

Finding links with partial text comes in handy when links have dynamic text. In this recipe, we will see how to use these methods to find links.

How to do it...

Let's create a simple test to see how finding links works in Selenium WebDriver with the following options.

Finding a link by its text

Selenium WebDriver's By class provides the linkText() method to locate links using text displayed for the link. In the following example, we will locate the Gmail link displayed on the Google Home page:

WebElement gmailLink = driver.findElement(By.linkText("GMail"));
assertEquals("http://mail.google.com/", gmailLink.getAttribute("href"));

Finding a link by partial text

Selenium WebDriver's By class also provides a method to locate links using partial text. This method is useful where developers create links with...

Finding elements by tag name

Selenium WebDriver's By class provides a tagName() method to find elements by their HTML tag name. This is similar to the getElementsByTagName() DOM method in JavaScript.

This is used when you want to locate elements using their tag name, for example, locating all <tr> tags in a table.

In this recipe, we will briefly see how to use the tagName() locator method.

How to do it...

Let's assume you have a single button element on a page. You can locate this button by using its tag in the following way:

WebElement loginButton = driver.findElement(By.tagName("button"));
loginButton.click();

Take another example where we want to count how many rows are displayed in <table>. We can do this in the following way:

WebElement table = driver.findElement(By.id("summaryTable"));
List<WebElement> rows = table.findElements(By.tagName("tr"));
assertEquals(10, rows.size());

How it works...

The tagName() locator method queries the...

Introduction


Web applications, and the web pages within these applications, are commonly written in a mix of Hyper Text Markup Language (HTML), Cascading Style Sheets (CSS), and JavaScript code. Based on user actions like navigating to a website Uniform Resource Locator (URL) or clicking the submit button, a browser sends a request to a web server. Web server processes this request and sends back a response with HTML and related resources, such as JavaScript, CSS, Images, and so on, back to the Browser. The information received from a server is used by the browser to render a web page with various visual elements, such as textboxes, buttons, labels, tables, forms, checkboxes, radio boxes, lists, images, and so on, on the page. While doing so, the browser hides the HTML code and related resources from the user. The user is presented with a graphical user interface in the browser window.

When we want to automate browser interaction using Selenium, we need to tell Selenium how to find a particular...

Using browser tools for inspecting elements and page structure


Before we start exploring how to find elements on a page, we need to analyze the page to understand the Document Object Model (DOM) tree, what properties or attributes are defined for the elements displayed on the page, how JavaScript or AJAX calls are made from the application, and so on.

Browsers use the HTML code written for the page to render visual elements in the browser window. It uses other resources, including JavaScript, CSS, images, and so on, to decide the look, feel, and behavior of these elements.

Here is an example of a BMI Calculator application page and the HTML code written to render this page in a browser, as displayed in the following screenshot:

You can view the code written for a page by right-clicking in the browser window and selecting the View Page Source option from the pop-up menu. This will display the HTML code of the page in a separate window, as shown in the following screenshot:

We need tools that...

Finding an element using the findElement method


Finding elements in Selenium WebDriver is done by using the findElement() and findElements() methods provided by the WebDriver and WebElement interface.

The findElement() method returns an instance of a WebElement that is found in the page DOM based on specified locators, also called search criteria. If it does not find an element using the specified search criteria, it will throw the NoSuchElementFound exception.

The findElements() method returns a list of WebElements matching the search criteria. If no elements are found, it returns an empty list.

Find methods take a locator or a query object as an instance of a By class as an argument. Selenium WebDriver provides a By class to support various locator strategies. The following table lists various locator strategies supported by Selenium WebDriver:

Strategy

Syntax

Description

By ID

Java: driver.findElement(By.id(<element ID>))

C#: driver.FindElement(By.Id(<elementID>))

Python...

Finding elements using the findElements method


Selenium WebDriver provides the findElements() method, using which we can find more than one element matching the specified search criteria. This method is useful when we want to work with a group of similar elements. For example, we can get all the links displayed on a page, or get all rows from a table, and so on.

In this recipe, we will get all the links and print their targets by using the findElements() method.

How to do it...

Let's create a test that will get all the links from a page, verify the count of links, and print a target for each link, as follows:

@Test
public void testFindElements() {
    //Get all the links displayed on Page
    List<WebElement> links = driver.findElements(By.tagName("a"));

    //Verify there are four links displayed on the page
    assertEquals(4, links.size());

    //Iterate though the list of links and print
    //target for each link
    for(WebElement link : links) {
        System.out.println(link...

Finding links


Selenium WebDriver provides two special methods to find links on a page. Links can be searched either by their text or by partial text.

Finding links with partial text comes in handy when links have dynamic text. In this recipe, we will see how to use these methods to find links.

How to do it...

Let's create a simple test to see how finding links works in Selenium WebDriver with the following options.

Finding a link by its text

Selenium WebDriver's By class provides the linkText() method to locate links using text displayed for the link. In the following example, we will locate the Gmail link displayed on the Google Home page:

WebElement gmailLink = driver.findElement(By.linkText("GMail"));
assertEquals("http://mail.google.com/", gmailLink.getAttribute("href"));

Finding a link by partial text

Selenium WebDriver's By class also provides a method to locate links using partial text. This method is useful where developers create links with dynamic text. In this example, a link is provided...

Left arrow icon Right arrow icon

Key benefits

  • Learn to leverage the power of Selenium WebDriver with simple examples that illustrate real-world problems and their workarounds
  • Explains the testing of mobile applications with Appium for mobile platforms such as iOS and Android
  • A pragmatic manual with engaging recipes and attractive screenshots to test your web applications efficiently

Description

This book is an incremental guide that will help you learn and use the advanced features of the Selenium toolset including the WebDriver API in various situations to build a reliable test automation. You start off by setting up the test development environment and gain tips on the advanced locater strategy and the effective use of the Selenium WebDriver API. After that, the use of design patterns such as data - driven tests and PageFactory are demonstrated. You will then be familiarised with extending Selenium WebDriver API by implementing custom tasks and setting up your own distributed environment to run tests in parallel for cross-browser testing. Finally, we give you some tips on integrating Selenium WebDriver with other popular tools and testing mobile applications. By the end of this book, you will have learned enough to solve complex testing issues on your own.

Who is this book for?

This book is intended for software quality assurance/testing professionals, software project managers, or software developers with prior experience in using Selenium and Java to test web-based applications. This books also provides examples for C#, Python and Ruby users.

What you will learn

  • Understand how the locators work and use various locator methods to build reliable tests
  • Build reliable and maintainable tests with the Selenium WebDriver API
  • Use the PageFactory pattern to build a robust and easy to maintain test framework
  • Build data-driven tests and extend Selenium API to implement custom steps and checks
  • Integrate and use ATDD/BDD tools such as Cucumber, SpecFlow, Capybara, and Behave with the Selenium WebDriver API
  • Set up iPhone/iPad and Android simulators and devices to test your mobile web application with Appium
  • Set up Selenium Grid for faster and parallel running of tests, increasing test coverage and reducing test execution time for cross-browser testing
  • Build extended Selenium WebDriver tests for additional coverage

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 30, 2015
Length: 374 pages
Edition : 1st
Language : English
ISBN-13 : 9781784390778
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Oct 30, 2015
Length: 374 pages
Edition : 1st
Language : English
ISBN-13 : 9781784390778
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 73.98
Learning Selenium Testing Tools - Third Edition
€36.99
Selenium Testing Tools Cookbook Second Edition
€36.99
Total 73.98 Stars icon
Banner background image

Table of Contents

15 Chapters
1. Getting Started Chevron down icon Chevron up icon
2. Finding Elements Chevron down icon Chevron up icon
3. Working with Elements Chevron down icon Chevron up icon
4. Working with Selenium API Chevron down icon Chevron up icon
5. Synchronizing Tests Chevron down icon Chevron up icon
6. Working with Alerts, Frames, and Windows Chevron down icon Chevron up icon
7. Data-Driven Testing Chevron down icon Chevron up icon
8. Using the Page Object Model Chevron down icon Chevron up icon
9. Extending Selenium Chevron down icon Chevron up icon
10. Testing HTML5 Web Applications Chevron down icon Chevron up icon
11. Behavior-Driven Development Chevron down icon Chevron up icon
12. Integration with Other Tools Chevron down icon Chevron up icon
13. Cross-Browser Testing Chevron down icon Chevron up icon
14. Testing Applications on Mobile Browsers Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(12 Ratings)
5 star 33.3%
4 star 66.7%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Yang Shanel Wang Jun 21, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I don’t know why I bought this book so author is winner because Science can include great sense of humor too. The purpose of invention of computer no matter software and hardware is to create convenience and happiness so human beings will have confidence stop fighting, no sadness, no discrimination.Computer codes are creatively changing and quality of production are improving because people love what they do so they never be dangerous to think consumers owe anything. I am lucky I am one of benefits especially it is very tough in recycle industry. I am grateful a lot of people put efforts to contribute, think others situations, and make people happy meanwhile it is bless I am around those people with good humble heart.
Amazon Verified review Amazon
Alexander Afanasyev Dec 27, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
What is really good about this book is that it contains tons of examples and recipes that you can try out in practice right away.The book contains quite a thorough example-based overview of the Selenium WebDriver API, from different element location techniques to mobile testing and selenium grids.
Amazon Verified review Amazon
Arun Motoori Dec 30, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I love this book among all the books available on Selenium. Few books help you get started, but this book stays with you from the beginning and continues to stay with you as reference. This book covers basic to advanced concepts of selenium in a simple and practical way. Topics like Configuring the Environment for developing Automation Scripts , Locators for finding various UI elements, Selenium API Commands along with their practical usage, latest framework concepts and many more are explained very well in a practical way. If you want to start learning or improve your knowledge on Selenium, just go for this book without any second thought.
Amazon Verified review Amazon
Priyanka Jan 27, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Helpful
Amazon Verified review Amazon
Amazon Customer Dec 31, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Its worthy
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.