Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Selenium Testing Tools Cookbook

You're reading from   Selenium Testing Tools Cookbook Unlock the full potential of Selenium WebDriver to test your web applications in a wide range of situations. The countless recipes and code examples provided ease the learning curve and provide insights into virtually every eventuality.

Arrow left icon
Product type Paperback
Published in Nov 2012
Publisher Packt
ISBN-13 9781849515740
Length 326 pages
Edition 1st Edition
Arrow right icon
Author (1):
Arrow left icon
UNMESH GUNDECHA UNMESH GUNDECHA
Author Profile Icon UNMESH GUNDECHA
UNMESH GUNDECHA
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Selenium Testing Tools Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Locating Elements FREE CHAPTER 2. Working with Selenium API 3. Controlling the Test Flow 4. Data-driven Testing 5. Using the Page Object Model 6. Extending Selenium 7. Testing on Mobile Browsers 8. Client-side Performance Testing 9. Testing HTML5 Web Applications 10. Recording Videos of Tests 11. Behavior-driven Development Index

Locating an element using the findElement method


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

The findElement() method returns a WebElement object based on a specified search criteria or throws up an exception if it does not find any element matching the search criteria.

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 query object as an instance of By class as an argument. Selenium WebDriver provides 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: driver.find_element_by_id(<elementID>)

Ruby: driver.find_element(:id,<elementID>)

Locates an element the using ID attribute

By name

Java: driver.findElement(By.name(<element name>))

C#: driver.FindElement(By.Name(<element name>))

Python: driver.find_element_by_name(<element name>)

Ruby: driver.find_element(:name,<element name>)

Locates an element using the Name attribute

By class name

Java: driver.findElement(By.className(<element class>))

C#: driver.FindElement(By.ClassName(<element class>))

Python: driver.find_element_by_class_name(<element class>)

Ruby: driver.find_element(:class,<element class>)

Locates an element using the Class attribute

By tag name

Java: driver.findElement(By.tagName(<htmltagname>))

C#: driver.FindElement(By.TagName(<htmltagname>))

Python: driver.find_element_by_tag_name(<htmltagname >)

Ruby: driver.find_element(:tag_name,< htmltagname >)

Locates an element using the HTML tag

By link text

Java: driver.findElement(By.linkText(<linktext>))

C#: driver.FindElement(By.LinkText(<linktext >))

Python: driver.find_element_by_link_text(<linktext >)

Ruby: driver.find_element(:link_text,< linktext >)

Locates link using it's text

By partial link text

Java: driver.findElement(By.partialLinkText(<linktext>))

C#: driver.FindElement(By.PartialLinkText(<linktext >))

Python: driver.find_element_by_partial_link_text(<linktext >)

Ruby: driver.find_element(:partial_link_text,< linktext >)

Locates link using it's partial text

By CSS

Java: driver.findElement(By.cssSelector(<css selector>))

C#: driver.FindElement(By.CssSelector(<css selector >))

Python: driver. find_elements_by_css_selector (<css selector>)

Ruby: driver.find_element(:css,< css selector >)

Locates element using the CSS selector

By XPath

Java: driver.findElement(By.xpath (<xpath query expression>))

C#: driver.FindElement(By.XPath(<xpath query expression>))

Python: driver. find_elements_by_xpath (<xpath query expression>)

Ruby: driver.find_element(:xpath,<xpath query expression>)

Locates element using XPath query

In this recipe, we will use the findElement() method to locate elements.

How to do it...

Locating elements using id, name, or class attributes is the preferred way to find elements. Let's try using these methods to locate elements as described in the following sections.

Finding elements by the ID attribute

Using the id attribute is the most preferable way to locate elements on a page. The W3C standard recommends that developers provide an id attribute for elements that are unique to each element. Having a unique id attribute provides a very explicit and reliable way to locate elements on the page.

While processing the DOM, browsers use id as the preferred way to identify the elements and this provides the fastest locator strategy.

Let's now look at how to use id attributes for locating elements on a login form.

<form name="loginForm">
    <label for="username">UserName: </label> <input type="text" id="username" /><br/>
    <label for="password">Password: </label> <input type="password" id="password" /><br/>
    <input name="login" type="submit" value="Login" />
</form>

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

To locate the User Name and Password fields, we can use the id attribute in the following way:

WebElement username = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("password"));

Finding elements by the Name attribute

Locating elements with the id attribute is the most preferred locator strategy, but you might find situations where you cannot use the id attribute due to the following reasons:

  • Not all elements on a page have the id attribute specified

  • The id attributes are not specified for key elements on a page

  • The id attribute values are dynamically generated

In this example, the login form elements use the name attribute instead of the id attribute:

<form name="loginForm">
    <label for="username">UserName: </label> <input type="text" name="username" /><br/>
    <label for="password">Password: </label> <input type="password" name="password" /><br/>
    <input name="login" type="submit" value="Login" />
</form>

We can use the name attribute to locate elements in the following way:

WebElement username = driver.findElement(By.name("username"));
WebElement password = driver.findElement(By.name("password"));

Unlike id, the name attribute may not be unique on a page. You might find multiple elements with similar name attributes and in such a case, the first element on the page with the specified value will be selected, which may not be the element you are looking for. This may cause the test to fail.

Tip

When building a testable application, you should recommend that the developers add the id attribute for key elements as well as other unique attributes to enable the easy location of elements.

Finding elements by the Class attribute

Apart from using the id and name attributes, you can also use the class attribute to locate elements. The class attribute is provided to apply CSS to an element.

In this example, the login form elements use the class attribute instead of the id attribute:

<form name="loginForm">
    <label for="username">UserName: </label> <input type="text" class="username" /></br>
    <label for="password">Password: </label> <input type="password" class="password" /></br>
    <input name="login" type="submit" value="Login" />
</form>

We can use the class attribute to locate elements in the following way:

WebElement username = driver.findElement(By.className("username"));
WebElement password = driver.findElement(By.className("password"));

How it works...

Selenium WebDriver API provides the findElement() method to locate the elements that are required in a test from the page under test.

When locating an element matching specified criteria, it looks through the DOM (Document Object Model) for matching elements and returns the first matching element to the test.

There's more...

The WebElement class also supports find methods that find child elements. For example, imagine that there are some duplicate elements on a page. However, they are located in separate <div> elements. We can first locate the parent <div> element and then locate the child element within the context of the <div> element in the following way:

WebElement div = driver.findElement(By.id("div1"));
WebElement topLink = div.findElement(By.linkText("top"));

You can also a use a shortcut method in the following way:

WebElement topLink = driver.findElement(By.id("div1")).findElement(By.linkText("top"));

NoSuchElementFoundException

The findElement() and FindElements() methods throw up the NoSuchElementFoundException exception when they fail to find the desired element using the specified locator strategy.

See also

  • The Locating elements using findElements method recipe

You have been reading a chapter from
Selenium Testing Tools Cookbook
Published in: Nov 2012
Publisher: Packt
ISBN-13: 9781849515740
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime