I am using using Selenium to write test automation with Javascript. Trying to extract class attributes of a DOM element does not work for me. Here is my code:
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.ie()).
build();
var usernameField = driver.findElement(webdriver.By.id('username'));
var classes = usernameField.getAttribute('class');
console.log(classes);
This prints the following:
{ then: [Function: then],
cancel: [Function: cancel],
isPending: [Function: isPending] }
Please indicate how to find the attribute values of the element.
The getAttribute() method fetches the text contained by an attribute in an HTML document. It returns the value of the HTML element's attribute as a string. If a value is not set for an attribute, it will return a NULL value. For attributes with Boolean values, getAttribute() will return either "True" or NULL.
We can find an element using the attribute class name with Selenium webdriver using the locators - class name, css, or xpath. To identify the element with css, the expression should be tagname[class='value'] and the method to be used is By. cssSelector.
Type “css=input[type='submit']” (locator value) in Selenium IDE. Click on the Find Button. The “Sign in” button will be highlighted, verifying the locator value. Attribute: Used to create the CSS Selector.
We can get the css class name of an element with Selenium webdriver. To obtain the class name attribute of an element in the html document, we have to use the getAttribute() method. Then the class value is passed as a parameter to the method.
Found the issue, console.log() was being fired asynchronously before any values were assigned. Forcing it to execute sequentially using then statement fixed the problem.
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.ie()).
build();
var usernameField = driver.findElement(webdriver.By.id('username'));
usernameField.getAttribute('class')
.then(function(classes){
console.log(classes);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With