DEV Community

Tony Colston
Tony Colston

Posted on

data-locators with Selenium (or the frontend dev stole my id)

What can you do if your front end developer will not let you use the ID? Or what if the class or name attributes keep randomly changing because of unamed Javascript Framework Number 3001?

There is another way to mark elements as unique and it is a well known good practice. It is called a data attribute. See my link at the bottom for more information.

You can have any HTML element and add any type of data on to that element as long as the name starts with "data-"

For instance if you had a button element you could mark it like this with a data- attribute.

<button id="32132132" class="red-button" data-id="loginbutton">click me</button>
Enter fullscreen mode Exit fullscreen mode

In the example above the data-id element has a value of loginbutton. You can use that to locate the element on the page. By using data-id that lets the front end developers use id/name/class as they normally and your tests will still just work.

Below is how you would locate that element in Selenium.

driver.find_element(By.CSS_SELECTOR, "[data-id='red-button']")
Enter fullscreen mode Exit fullscreen mode

The name data-id is not special. You can make your data- elements more domain specific. Like data-username or data-password or data-statedropdown. Anything that makes sense to your site or domain.

This is a great way to involve your front end developers with QA/testing. Get your front end devs to add specific data- elements to their markup. They can help you make the tests more robust and hopefully make both of your lives easier.

I will show one example for a local web site that I have running on my machine. I made an HTML element that had a data- element that looks like this (I picked an odd name just to show that the name does not matter).

<a href="test.html" data-frog="burp">hey</a>
Enter fullscreen mode Exit fullscreen mode

from selenium import webdriver
from selenium.webdriver.common.by import By

import time
driver = None

try:
    cpath = "e:\\projects\\headless\\chromedriver.exe"
    driver = webdriver.Chrome(cpath)
    driver.get("http://localhost:2015/")
    e = driver.find_element(By.CSS_SELECTOR,"[data-frog='burp']")
    print(e)
    e.click()
    driver.save_screenshot("test0.png") 
finally:
    if driver is not None:
        driver.quit()
Enter fullscreen mode Exit fullscreen mode

https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

Top comments (2)

Collapse
 
vsreelasya profile image
Sree Lasya Vallabhaneni

Awesome Post! I have used data- elements in my previous workplace and this worked much better and reliable way than depending on the id/XPath selectors.

Collapse
 
zac11 profile image
Rahul Yadav

Great one.