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.
- Unique ID being generated for every session (with random alphanumeric characters)
- Repeated class names for various elements
- 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,
- The attribute name should start with
- After this prefix of
data-, the attribute name should at least be one character long and must be in lowercase letters only
- The value provided for this attribute can be any string.
That’s pretty special, don’t you think?
Here goes an example for better visualization of the concept,
With these data attributes in place, locating elements become a piece of cake!
WebElement poultry = driver.findElement(By.
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.<< 9ab. WebDriver – Using Actions Class 10a. Advanced WebDriver – Using Apache ANT >>