Learning Selenium Testing Tools(Third Edition)
上QQ阅读APP看书,第一时间看更新

Chapter 2. Locators

Locators allow us to find elements on a page that can be used in our tests. In the last chapter, we managed to work against a page that had decent locators. In HTML, it is seen as a good practice to make sure that every element you need to interact with has an ID attribute and a name attribute. Unfortunately, following best practices can be extremely difficult, especially when building HTML dynamically on the server before sending it back to the browser.

In this chapter, we will cover the following topics:

  • Locate elements by ID
  • Locate elements by name
  • Locate elements by link
  • Locate elements by XPath
  • Locate elements by CSS
  • Locate elements by DOM

So, let's get on with it.

Note

Before starting this chapter, we should begin by making sure that we have all the relevant applications installed. While these are not foolproof, they will give us an idea of how to construct the locator for our tests.

The following are the browser add-ons that will help us inspect and locate the web elements:

  • Firebug: Firebug (https://addons.mozilla.org/firefox/addon/firebug) has become the de facto tool for web developers as it allows them to find elements on the page by using the find functionality. It has a JavaScript REPL (Read-Eval-Print-Loop) or an interactive shell that allows you to run JavaScript without having to create an entire page.
  • Firefinder: Firefinder (https://addons.mozilla.org/firefox/addon/firefinder-for-firebug) is a very good tool for testing out XPath and CSS on the page. It will highlight all elements on the page that match the selector to your element location.
  • IE Developer Tools: This is a built-in tool in IE7, IE8, and IE9 that we can launch by pressing F12. It also has a number of features that Firebug has in common with.
  • Google Chrome Developer Tools: This, like IE, is a built-in feature in the browser and will also allow you to find elements on the page and be able to work out its XPath.

Once you have worked out your locator, you will need to put it into Selenium IDE to test it, and verify that the element is located properly. In the layout of Selenium IDE, one of the buttons on the page is named Find. Click on this button when you have something in the Value textbox; it will highlight the item in green, as shown in the following screenshot. On Mac OS X, the background color will flash yellow:

Locators

Now that we have these tools and understand how to use them, we can start adding locators to our test scripts.