Web element locator

Web element locators are used in UI test automation to identify unique elements within a webpage. It is important to have good locators to find the correct web elements, making sure that tests are faster, more accurate, and more maintainable. Locating web elements, however, isn’t that easy.

Anyone who does some kind of web UI test automation, with Selenium WebDriver for example, is likely to spend a big portion of their test development time trying to locate elements on a web page. Web elements could be anything that the user sees on the page, such as text fields, links, buttons, dropdowns, or any other HTML element.

Finding the right web elements is a vital requirement when creating an automation script, but it can be challenging. Frankly, it’s probably one of the biggest stumbling blocks in test automation.

Often, we end up working with incorrect or inconsistent web GUI elements, such as those lacking unique IDs or class names, or those which IDs or names vary from release to release, making it hard or even impossible to find the correct elements on the page. Failure to identify elements on a web page may result in less reliable tests.

What are web element locators?

Locators are basically the HTML attributes of a web element. They help identify unique web elements on a page and command testing frameworks, such as Selenium WebDriver, to perform the action on those elements. Locators are also known as selectors.

There are several types of web element locators in WebDriver, including:

  • ID – Used to identify web element with an ‘ID’ attribute
  • Name – Used to locate an element with a ‘name’ attribute
  • Link Text – Used to identify the hyperlinks on a web page with the help of ‘<a>’ (anchor) tag
  • CSS Selector – Used to locate complex elements on the page
  • XPath – A language to query XML documents, consisting of a path expression along with some conditions

How do we usually find web elements on a page?

ID locators and Name locators are generally regarded as the most popular and the fastest way to identify web elements. To see how ID locators work, open Yahoo login page in Google Chrome, right-click an element on the web page, for example, a login field, and then select ‘Inspect.’

The ID locator looks for the ‘ID’ attribute as shown in the image.

This is a portion of code we’d use in Selenium to automate the action that would send values using the ID locator:

driver.get("https://login.yahoo.com/");
driver.findElement(By.id("login-username")).sendKeys("[email protected]"); //id locator for text box
WebElement searchIcon = driver.findElement(By.id("login-signin"));//id locator for next button
searchIcon.click();

Similarly, Name locators try to identify elements with the ‘name’ attribute.

This is how it looks when we want to automate it:

driver.get("https://www.google.com");
driver.FindElement(By.name("btnK")); searchButton.Last().Click();

IDs and names are a great choice for test automation as they make it incredibly simple to write locators with short queries and no extra anchors. This method, however, only works if developers write unique and consistent IDs or names for elements that don’t vary from release to release, which is not always the case.

For elements that lack unique identifiers, we must use more complicated locators, such as CSS selectors and XPath.

But, before we start explaining how to identify web elements using these two locator types, let’s check out Link Text locators.

Out-of-The-Box Web Test Automation

for Selenium or Protractor

Link Text Locators

We use this type of locator to identify the hyperlinks on a web page with the help of an anchor tag (<a>).
We’ll again use the Yahoo login page as the example. Right-click on the ‘Difficulty signing in?’ link and review the code.

Here’s how we automate it in Selenium WebDriver:

driver.get("https://login.yahoo.com/");
driver.findElement(By.linkText("Difficulty signing in?")).click();

Using these types of locators is ideal when testing navigation on the page, however, we need to know the exact names of the links.

CSS Selectors

A CSS selector is usually the best possible way to locate one or more elements in the web page, including those having no ID, class, or name. This way is faster and more readable than other locators. However, creating CSS selectors is not easy because they tend to be more complex and require a deeper understanding of CSS and JavaScript.

There are several types of CSS selectors. Each is used differently.

We have simple selectors that help us identify one or more elements based on element Class or ID. Refer to the following code example:

driver.findElement(By.cssSelector("#id"));
driver.findElement(By.cssSelector(".class"));

There are attribute selectors to find one or more elements based on their attributes and attribute values. Here’s the example in code where we use the Name attribute to locate an <input> element:

driver.findElement(By.cssSelector("input[name=username]"));

CSS selectors enable you to locate elements matching partial attribute values. This is very useful for testing applications where attribute values are dynamically assigned and change every time a page is requested.

We use the following CSS partial match syntax: ^= (starting with), $=(ending with), *= (containing)

Pseudo-classes are used to locate one or more elements that exist in a certain state, for example, elements being hovered over by the mouse pointer, or those disabled or checked.
For example:
:hover, :disabled, :checked, etc.

Pseudo-elements are used to style specified parts of an element, such as the first word of each paragraph, or to insert content before or after the content of an element.
For example:
::after (:after), ::before (:before), ::first-line (:first-line), etc.

Combinators are not selectors per se, but ways to combine two or more selectors to define specific selections. Sometimes one CSS selector may not be sufficient to locate an element, for example, one attribute, so we need to combine additional attributes for a precise match.

Here is an example of combinator use when we want to locate an element with two attributes:

driver.findElement(By.cssSelector("input[type='submit'][value='Login']"));

Similarly, multiple selectors are not separate selectors, but multiple selectors placed under the same CSS rule to apply a single set of declarations to all the elements selected by those selectors.

Here’s the example in which we use the element’s Id, class, and attribute value:

driver.findElement(By.cssSelector("#id .class input[type=text]"));

There’s a lot more to learn about CSS selectors as well as when and how to use them, such as universal selectors used to match elements of any type, sibling combinators, substring matching attribute selectors, structural pseudo-classes, etc.

Sounds complicated? You bet.

XPath locators

Using XPath locators is more efficient than using CSS selectors to find multiple elements on a web page. However, they’re even more complicated than CSS selectors. In fact, XPath locators are the most complex selectors to use.
XPath is a language to query XML documents and using XPath locators requires knowledge in XPath query language. So, it may be hard for anyone who is not familiar with this language to locate web elements using XPath.

Here’s how we use XPath locators when looking for web elements:

  • In Google Chrome, navigate to google.com and inspect the ‘Search’ field.
  • On inspecting the web element, we can see it has a ‘class’ attribute that we’ll use to construct an XPath locator which in turn will locate the ‘Search’ field.
  • Next, click Elements tab and press Ctrl + F to open a search box in Chrome’s DevTools. Here, we’ll write the XPath like this:
//*[@class='a4bIc']

Or, in Selenium, this is how the code would look:

driver.findElement(By.xpath("//*[@class='a4bIc']"));

To locate the ‘Google Search’ button, we’d use this, a slightly different XPath:

//input[@name='btnK']

These are just basic XPath examples. But, as with CSS Selectors, using XPath locators is a broad subject that can’t be explained in a single article. Things such as methods, expressions, and functions used in XPath require knowledge, but also the time that many developers in test automation lack.

How to make it simple and faster?

The goal of testing is to make things as simple as possible so that we can focus on actual testing rather than coding or fixing the code. Finding and identifying web elements by manually writing CSS Selectors or XPath can be bothersome for many testers who want to speed things up.

Accelerating the testing process is actually possible with Ranorex Selocity, a free Chrome extension that auto-generates robust and reliable CSS, XPath and RanoreXPath selectors in the Chrome DevTools. You can use this extension with any IDE of your preference, but you’ll achieve the best results if you connect Ranorex Selocity to Ranorex Webtestit, the IDE for testing with Selenium and Protractor.

In the example below, we’ll demonstrate how to auto-generate locators with Selocity and send them directly to Ranorex Webtestit with just a few clicks.

First, open Ranorex Webtestit and create a new project or open an existing one.

Then, you need to install the Ranorex Selocity extension.

Open google.com in Google Chrome. We’ll try to identify the ‘Google Search’ button.

Click F12 to open Chrome DevTools on Windows/Linux, or Command + Option + I on MacOS. Find Ranorex Selocity in the Elements section (if you don’t see it, reload the page or expand the DevTools window.)

Connect Ranorex Selocity to Ranorex Webtestit with a click.

In Ranorex Webtestit, create a Page Object.

Better yet, you can create it directly from the Google Chrome DevTools page by clicking on ‘Create new Page Object’ button in the Selocity menu and then selecting the area of the page.

On the Google page, right-click on the element (button). You’ll see the list of selectors, including CSS, XPath, and RxPath.

Click on the ‘Send selector to Ranorex Webtestit’ button next to the selector’s name. We’ll send XPath.

The selector will be sent automatically to your Page Object in Webtestit. You can also view the screenshot of an element.

The imported element will have the default name (btnK) but you can rename it to something more coherent, such as searchButton or whatever else you prefer.

To initiate the action on the newly added element, simply drag and drop the element from the Elements tab into the Page Object code and choose one of the actions from the drop-down menu (in this case: Do > Click on element).

The action will be added to the code automatically. It will have a default name performNewAction which you can also change.

After you’ve added all necessary elements with the Ranorex Selocity extension, you can start writing your test which is also simple if you do it with Ranorex Webtestit.

Here’s a useful step by step guide on how to create a project and run your tests with Ranorex Webtestit.

If you use other testing frameworks, you can still utilize Ranorex Selocity to auto-generate selectors. Simply right-click the element and choose ‘Selector actions’ then ‘Copy css,’ ‘Copy xpath,’ or ‘Copy rxpath’ from the drop-down menu and paste them manually into your code.

It’s not as convenient as sending selectors directly to your code in Ranorex Webtestit, but it could still save you from writing all selectors manually.

Conclusion

As you can see, finding web elements doesn’t have to be a pain in the neck. The free Chrome extension, Ranorex Selocity, helps you handle complex CSS Selectors and XPath locators by generating them automatically with a single click. Moreover, if you use Ranorex Selocity with Ranorex Webtestit, these locators can be sent directly to your test code.

You can download a free, full-featured trial of Ranorex Webtestit and connect it to the free Ranorex Selocity extension and immediately discover all the advantages of painless testing.

Out-of-The-Box Web Test Automation

for Selenium or Protractor