The Complete Guide to Getting Attribute Data with Selenium JavaScript
Greetings automation tester!
Are you struggling to reliably get attribute data while testing web apps? Well struggle no more – you have discovered the complete guide to crack attributes testing using Selenium JavaScript!
Over my 10+ years as lead automation architect, I have tested on 3000+ browser and device configurations. In this journey, dealing with dynamic attributes remained one of the top test engineering challenges.
This comprehensive handbook shares all my learnings to help you become an expert in getting attribute values for robust test automation.
I will explain concepts using simple terminology and guide you through actionable tutorials. By the end, attributes testing will no longer be intimidating!
So let‘s start unraveling…
Introduction to Attributes
But first – what exactly are attributes?
In a nutshell, attributes provide additional information about HTML elements through key-value pairs in opening tags.
Some examples are:
<button class="btn-primary" id="submit">Send</button>
<img src="logo.png" alt="company logo">
Here class, id, src and alt are attributes used by the tags.
You are wondering – why should I care about them as a tester?
Here are 3 key benefits attributes provide in test automation:
-
Uniquely identify elements using
id,nameorclassattributes. This prevents flaky locators. -
Retrieve state using values of attributes like
src,href,disabledetc. Simplifies assertions. -
Parameterize tests by externally controlling attribute values used in test data. Enables reusability.
However, attributes pose challenges too…
For instance, UI elements get updated frequently leading to changing attribute values. Dealing with such dynamic attributes requires special handling.
Overall, knowledge of attributes testing becomes imperative for writing automated checks that provide sufficient test coverage across web apps.
Let‘s learn how to get attribute data programmatically using Selenium!
Methods to Access Attributes
Selenium WebDriver JavaScript bindings provide two handy driver methods:
getText()
This returns the visible innerText from elements by extracting raw text between tags.
Example:
//For element <button>Save Changes</button>
let text = driver.findElement(By.tag(‘button‘)).getText();
//text = "Save Changes"
✅ Pros: Simple, directly gets visible text
❌ Cons: Doesn‘t return attributes, prone to CSS overlaps
getAttribute()
This more flexible method returns value of any specified attribute from the element.
Example:
//For element <button class="btn-primary">Save</button>
let cls = driver.findElement(By.tag(‘button‘)).getAttribute(‘class‘);
//cls = "btn-primary"
✅ Pros: Customizable, works for any attribute
❌ Cons: Slightly more code than getText()
So in summary:
getText()- Great for visible text between tags
getAttribute()- When you need any attribute value like id, src etc.
Now that you know how to get attributes in Selenium JavaScript, let‘s apply this in a test script.
Step-by-Step Tutorial on Extracting Attributes
We will write a script to:
- Initialize WebDriver
- Open sample website
- Get src of logo image
- Validate attribute value
Prerequisites
Make sure to have:
✔️ Node.js
✔️ WebDriver package
✔️ Browser driver – Chrome/Firefox etc
Here are setup commands:
#Install webdriver package
npm install selenium-webdriver
#Install appropriate driver
npm install chromedriver
With this done, let‘s code the test!
Test Script
//Initialize webdriver instance
const {Builder} = require(‘selenium-webdriver‘);
(async function example() {
let driver = await new Builder().forBrowser(‘chrome‘).build();
//Open site
await driver.get(‘https://example.com‘);
//Find logo image
let logo = driver.findElement(By.css(‘header img‘));
//Extract src attribute
let srcValue = await logo.getAttribute(‘src‘);
//Validate
assert.equal(srcValue, ‘site-logo.png‘);
await driver.quit();
})();
Key Steps:
- Get logo web element using CSS selector
- Use
getElement().getAttribute()to extract src - Assert expected logo file name
This validates if the image rendered has the correct src mapped!
Running Tests
Execute tests using:
mocha attribute_test.js
And integrate in CI/CD pipelines to run on commits.
This was a simple example. Now let‘s explore some best practices!
Tips and Best Practices
Over the years, I have compiled a list of top recommendations:
🔹 Parameterize attribute values for configurable data driving
//Centralized test data file
{
"url": "https://webapp.com",
"logo_src": "imgs/logo.png"
}
//Import and reference in script
let data = require(‘./data.json‘);
await driver.get(data.url);
let src = getLogoImageSrc(); //Extracted dynamically
assert.equal(src, data.logo.src);
This keeps test logic reusable across environments!
🔹 Handle dynamic attributes by asserting only stable parts:
let classNames = element.getAttribute(‘class‘); //format: btn btn-primary
//Assert presence of btn-primary
assert.isTrue(classNames.includes(‘btn-primary‘));
🔹 Centralize extract logic through Page Objects:
// page_objects/base_page.js
class BasePage {
async getText(locator) {
let element = await driver.findElement(locator);
return element.getText();
}
async getAttribute(locator, attribute) {
let element = await driver.findElement(locator);
return element.getAttribute(attribute);
}
}
// tests/login_test.js
let page = new BasePage();
let heading = await page.getText(By.css(‘h1‘));
let url = await page.getAttribute(logo, ‘src‘);
This reduces code duplication!
There are many more pro techniques to master like dealing with stale elements, log capturing, cross-browser testing etc.
Over time, you will learn to handle every scenario related to attribute testing!
Debugging Attribute Issues
Here are some tips for troubleshooting:
💡 Use locator tools like developer console to validate element properties
💡 Log extracted attributes to console for diagnosis
💡 Handle StaleElementReference exceptions for changed elements
💡 Compare behavior across browsers for inconsistencies
And the golden rule – fail fast but safely!
Additional Concepts
While this guide focused on web testing, attributes form a core building block across test types:
Mobile Testing
Inspect native app elements using tools like Appium Desktop to get attributes in the visual view hierarchy.
API Testing
Many HTTP headers like Content-Type act as attribute metadata for requests and responses.
So learning to extract attribute data flexibly will prove invaluable in your automation journey!
Conclusion
Let‘s summarize the key points:
✔️ Attributes provide supplementary data about HTML elements
✔️ getText() and getAttribute() help get attributes in Selenium
✔️ Parameterization and encapsulation help manage attributes
✔️ Proper handling of dynamic changes is needed
With these learnings, you are now equipped to harness attribute based testing!
As you practice more, share feedback and any issues faced in the comments section. I will try my best to help out.
Happy attributes testing!