9ac. WebDriver – Unable to locate an element easily? Read on…

Well, if your memory is better than mine, then you will remember that we have 8 locator types in Selenium WebDriver viz., ID, name, tag name, class name, link text, partial link text, CSS selector and XPath. The sad part is, even though we have these many locator types, it still gets challenging to locate an element, especially when the application under test is complex.

For instance,

  1. Unique ID being generated for every session (with random alphanumeric characters)
  2. Repeated class names for various elements
  3. Multiple div tags making XPaths longer than usual

All these make an automation tester’s job extra challenging! Absolute XPaths can be helpful but if a new element is included in the DOM or an existing element is moved around a bit, then the chances are that the script might fail as the element would not be found. Relative XPaths might come to the rescue but even then, the whole process gets difficult as the script gets complicated.

The easy and best way to handle such situations is to introduce data-* attributes (custom data attributes) on HTML elements. The only catch here is, you will need to be in the good books of the developer! 😉 He/she is the one to add these attributes to the code as per your requirement.

Let me school you on these custom data attributes now,

The custom attribute allows us to store extra data or information on the HTML elements. The rules to be followed are,

  1. The attribute name should start with data-
  2. After this prefix of data-, the attribute name should at least be one character long and must be in lowercase letters only
  3. The value provided for this attribute can be any string.

Syntax: <element data-*="value">

That’s pretty special, don’t you think?

Here goes an example for better visualization of the concept,

<li data-test=”poultry”>Chickens</li>

With these data attributes in place, locating elements become a piece of cake!

WebElement poultry = driver.findElement(By.xpath("//li[@data-test='poultry']"));

And, it is as simple as that! Go ahead and experiment a bit, feel free to post your questions in the comments section.

See you again in another article.

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.