Locator Strategies for Web Elements
A Web page is a document on the world wide web that can be displayed in a browser. There is quite a bit of content in a web page as in title, paragraphs, images, lists, links, and more.
Users engage visually with web pages, which is a crucial aspect of web pages. They can scroll to view more text in large images and even click links to go to new articles by scrolling. Users do not need to know any particular commands, and websites that provide a good user experience make interactions intuitive and easy.
What makes a Web page interactive?
There are three main components under the hood that people never see.
- HTML (HyperText Markup Language)
Acts as the Skeleton of the web page. It lays the groundwork for all of the content. HTML is a Markup Language, not a programming language in and of itself. It just states what should be displayed.
<!-- HTML Format -->
<tagname attribute="value"> textContent </tagname>
2. CSS (Cascading Style Sheets)
Acts as the skin of the webpage where styling can be added controls things like color, size, font, position, layout. You can use an HTML tag using ‘style’ or can have a separate .css file for reusability.
body {
background-color: lightblue;
}
.main-content {
Font-family: Helvetica;
}
3. JavaScript
Dynamic content comes through JavaScript - the muscles of the page. As those major web browsers support JavaScript, nearly all current online applications employ it to provide a dynamic user experience on the front end. JavaScript code can be written directly in HTML files, or as a better practice, in separate .js
files.
alert("Here's some JavaScript!");
Programming with DOM
‘Document Object Model’ is a programming interface for HTML and XML documents. HTML, CSS, and JavaScript are all coded documents that are combined into a visual web page by a web browser. When a browser renders a page and subsequently executes it, it requires an interface to manipulate the web page.
Getting the elements themselves is the first step with DOM programming. It emphasizes one point: there is a distinction between an element and its locator.
A Web Element is an object that represents a page’s live depicted HTML element. A Web element locator, on the other hand (sometimes known as a “selector”), is a query that searches the DOM for and returns certain elements. In a nutshell, locators look for items.
Some of the Locator types are ID, Name, Class name, CSS Selector, Xpath
There are numerous ways to interact with element objects once they have been received. You should be aware that a locator can return multiple elements rather than just one. It’ll give you a list of all the elements it finds that fit the query.
Finding live web elements
When automating web UI tests, manually locating items is critical. Developers don’t always provide locators for all elements, therefore we have to find them ourselves as testers. For this, you can use the Developer Tools on the browser.
Click the “select” tool in the upper left corner of the DevTools pane to visually locate an element.
Choosing the best locator
It can be difficult to come up with good locators. Always keep in mind that a locator will return all components that match the query.
- If a locator’s scope is too broad, it may produce false positives.
- If a locator is too specific, it may break when the DOM changes, and it may be difficult to read for others.
So, writing the simplest locator query that uniquely identifies the target element or elements is the best strategy.
The id
attribute on a particular page must have a unique value according to HTML standards.
Another good locator is the name
attribute. For input-related elements such as input, button, and text area, name attributes are utilized.
A third basic locator is CSS class
name. CSS styling is applied to HTML components through class names. They can, however, be used as de facto identifiers.
Additionally, class names do not have to be unique for each element. Multiple items may share the same class name. When looking for a group of components, such as a list of search results, this is beneficial.
IDs, names, and class names are the easiest locators to use and the best type of locators can be ordered as;
ID > Name > Class > CSS Selectors > Xpath
CSS Selectors are expressions that find elements on a webpage by matching patterns.
Basic CSS Selector Examples
- Tag name:
div
- Class name:
.result
- Tag and class name:
div.result
- ID :
#search_form_input
- Descendants :
div.cw div.result
- Direct parent-child relationship :
div.cw > div.result
- Direct Children:
li.zcm__item > a
- Multiple Selectors:
ol > li, ul > li
The ability to pick components based on their characteristics is another useful feature of CSS Selector syntax.
- Attribute existence:
[style]
- Tag with attribute:
div[style]
- Tag with attribute equality:
a[data-zci-link = 'images']
- Tag with attribute contains:
div[class*='result']
We can do even more advanced conditions with pseudo-classes.
- Logical not pseudoclass:
div.result:not(.result--more)
- Nth child pseudoclass:
div.result:nth-child(3)
We can easily use similar CSS Selectors to get all these different kinds of elements together via chaining.
- Locate by the link itself
div.footer_cards a[data-id='traffic']
- Locate by the title
div.footer_cards a[data-id='traffic'] .footer__card__title
- Locate by the icon
div.footer_cards a[data-id='traffic'] .footer__card__icon
- Locate by the text
div.footer_cards a[data-id='traffic'] .footer__text
- Locate by direct parent-child arrow ‘>’
div.footer_cards a[data-id='tips'] > .footer_card_icon
However, it’s better to keep things simple but understandable and distinct.
As you begin writing your own CSS Selectors, keep this in mind. CSS selectors are excellent for locating web elements. The elements they select can be even more particular than IDs and class names. Because they use CSS syntax, most web developers are already familiar with them. When writing CSS Selectors, always remember to test them.
CSS Selectors aren’t all-powerful, either. They are unable to identify any element on the page in a unique way. CSS Selectors can’t always pick elements based on their text context, and they can’t always pick elements based on their index.
That’s where Xpaths come in to play.
Basic Xpaths Rules
- Locate by Path from Root
/html/body
- Locate by Tag
//input //button
- Locate direct children
//ul/li/a
- Locate by any element
//*
- Locate by any descendent
//div//
- Locate by Attribute value equality
//li[@class='zcm__item']
XPaths can also have logical AND and OR operations for those conditional phrases.
- Locate by Attribute Condition AND
//img[@width<20][@height<20] //img[@width<20 and @height<20]
- Locate by Attribute Condition OR
//input[@name='q' or @id='search_form_input']
Another very powerful part of the XPath Syntax is its set of functions which really help to make better attribute conditions.
- Locate by Contains Function
//div[contains(@class = 'result__snippet')]
- Locate by Starts with Function
//div[starts-with(@class, 'result')]
- Locate by Logical not Function
//a[not(contains(@class, 'header'))]
- Locate by the combination of not starts with
//a[not(starts-with(@class, 'header'))]
There are many more XPath functions available and never stop looking for them online.
Advanced Xpath
When an element lacks any distinguishing characteristics, the only method to identify it is via its text content. Text can also be used as a filter in some cases.
- Multiple contains conditions :
//div[contains(@class, 'result__snippet')][not(contains(., 'bamboo'))]
- By index:
(//div[contains(@class, 'result__snippet')])[3]
- Multiple tag combination :
//a[.//img]
- Axes for relationships (preceding) :
//a[contains(@class, 'zcm__link')][preceding::a[@data-zci-link='web']]
- Axes for relationships (following) :
//a[contains(@class, 'zcm__link')][following::a[@data-zci-link='videos']]
There are a few other types of locators worth learning and then we can stack them to see which ones are best.
- Link Text
driver.findElement(By.linkText("Search by"));
- PartialLink text
driver.findElement(By.partialLinkText("Search"));
- Tags
driver.findElement(By.tag("a"));
Now that we know all the different types of web element locators, it’s time to answer the million-dollar question — which one is the best one to use?
When we write locators for test automation, we should be keen to use the simplest locator possible to uniquely identify the desired element or elements.
Order of preference:
- ID
- Input name
- Class Name
- CSS Selector
- XPath without text or indexing
- Link Text or Partial Link text
- XPath with text and/or indexing
Hope it was a good read. See you soon :)
Happy Testing!!!