Locating Elements
One of the most important features of Watir is the many varied ways it allows users to locate elements. The Watir location API is designed to be easily read and understood by users (humans). Elements are located by creating a Selector Hash, which Watir translates into the potentially complicated information the driver needs to know to identify the element.
The special cases will be highlighted below, but Watir Locators:
- Accept
String
values for exact matching - Accept
RegExp
values for partial matching - Can be mixed with any other Watir Locator
- Can be used to find the first matching element, or all matching elements as part of a collection
Firstly, like Selenium, Watir supports the full power of directly using :css
& :xpath
selectors. When
either of these are used, they must be the only one provided in the Selector Hash.
Watir’s goal, however, is to minimize the need to rely on these powerful locators.
XPath in particular can be difficult to read and can be easy to
write in a brittle fashion, so Watir encourages the approach of “No More XPath!”
Additionally, it is worth noting that there are two locators defined in the WebDriver specification
that Watir does not directly support because it provides the same functionality by alternate means.
These are :link_text
and :partial_link_text
.
With Watir you can locate any element by its text, not just links, and Watir already supports
partial matches for all of its locators with Regular Expressions.
Standard Watir Locators
ID
Name
Tag Name
Class Name
Text
Visible Text
Data Attributes
Aria Attributes
Valid or Custom Attributes
Label
Index
- this can not be used to locate an element collection
- when combined with other locators, index is the last filter to be applied)
Presence/Absence/Multiple Classes
- this takes an Array of String or RegExp values
Presence/Absence Attributes
- this takes a Boolean value
Visible
- this takes a Boolean value
Adjacent Nodes
- these are not locators in the Selector Hash
- these are methods that accept a Selector Hash
Implementation Details
Most of the time Watir can translate the Selector Hash into a single XPath expression to quickly identify the element.
You can get a sense for what this looks like by checking out our sample app XPathify.
Instances where this can not be done include when the usage of :visible
, :visible_text
or :index
locators,
or (sometimes) when there are Regular Expressions in the locator values. In that case Watir locates
potentially matching elements and iterates over them to provide the requested result.