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

Arrow left icon
Profile Icon UNMESH GUNDECHA
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (12 Ratings)
Paperback Oct 2015 374 pages 1st Edition
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon UNMESH GUNDECHA
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (12 Ratings)
Paperback Oct 2015 374 pages 1st Edition
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. €18.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781784392512
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. €18.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Oct 30, 2015
Length: 374 pages
Edition : 1st
Language : English
ISBN-13 : 9781784392512
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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.