Selenium Locators

Background

For many Selenium commands, a target is required. This target identifies an element in the content of the web application, and consists of the location strategy followed by the location in the format locatorType=location. The locator type can be omitted in many cases. The various locator types are explained below with examples for each.http://www.seleniumhq.org/docs/02_selenium_ide.jsp#locating-elements

A Note on Locators

Most locators will find the first element that matches the criteria. So, if you have “link=Click Here” as your target and you have multiple “Click Here” links on the page, then Selenium will run with the first one it find in the DOM.

Selenium IDE

While using Selenium IDE it will chose the selector for you. Most often this is fine but in the case of dynamic IDs, you’ll need to know how to make your own. The order in which Selenium IDE picks a selector seems to be:

ID

Link Text (for <a> only)

Name + Type (optional) + Value (optional)

Xpath

There are other locators, but I have yet to see Selenium IDE use them. You can see all of them by clicking on the link in the Background quote (above).

Locating By ID

This is probably the simplest as an ID should be unique. A challenge would be if the ID is dynamic. If so, use another locator method (below).

To target the <input> whose name is “continue”, type is “button”, and value is “Clear” your target will be name=continue type=button value=Clear. Note that if you don’t specify a value, then Selenium will find the element whose value is “Login” as it is the first element to meet the conditions.

Locating by Xpath

Xpath was intended for XML but works with HTML as well. This uses an elements position in the DOM as a locator. An Xpath of html/div/a[1] would look in the <html> section of the DOM, drill down into the first <div>, and then find the first <a>.

Locating with CSS Instead of Xpath

Xpath is great when it works. When it doesn’t it’s usually because the element changed position in the DOM. For this reason we should target elements in a way that front-end developers would. That is CSS selectors. To do so your target will be css={insert path here}

Tips on Building Xpath and CSS Locators

In Chrome you can inspect an element, right-click, and select ‘Copy CSS Path’ or ‘Copy Xpath’.

In Firefox you can do the same thing but you will need the Firebug add-on.