I have been testing using Selenium WebDriver and I have been looking for an XPath code to get the value of the attribute of an HTML element as part of my regression testing.
You can use the getAttribute()
method.
driver.findElement(By.xpath("//div[@class='firstdiv']")).getAttribute("alt");
Selenium Xpath can only return elements. You should pass javascript function that executes xpaths and returns strings to selenium.
I'm not sure why they made it this way. Xpath should support returning strings.
Using C#, .Net 4.5, and Selenium 2.45
Use findElements to capture firstdiv elements into a collection.
var firstDivCollection = driver.findElements(By.XPath("//div[@class='firstdiv']"));
Then iterate over the collection.
foreach (var div in firstDivCollection) {
div.GetAttribute("alt");
}
Just use executeScript
and do XPath or querySelector/getAttribute
in browser. Other solutions are wrong, because it takes forever to call getAttribute
for each element from Selenium if you have more than a few.
var hrefsPromise = driver.executeScript(`
var elements = document.querySelectorAll('div.firstdiv');
elements = Array.prototype.slice.call(elements);
return elements.map(function (element) {
return element.getAttribute('alt');
});
`);