How to get the value of an attribute using XPath

40,375

Solution 1

You can use the getAttribute() method.

driver.findElement(By.xpath("//div[@class='firstdiv']")).getAttribute("alt");

Solution 2

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");
        }

Solution 3

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.

Solution 4

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');
        });
  `);
Share:
40,375

Related videos on Youtube

arn-arn
Author by

arn-arn

Updated on November 17, 2020

Comments

  • arn-arn
    arn-arn about 2 years

    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. But I couldn't find a good answer.

    Here is my sample html element:

    <div class="firstdiv" alt="testdiv"></div>
    

    I want to get the value of the "alt" attribute using the XPath. I have an XPath to get to the div element using the class attribute which is:

    //div[@class="firstdiv"]
    

    Now, I am looking for an XPath code to get the value of the "alt" attribute. The assumption is that I don't know what is the value of the "alt" attribute.

    • Arran
      Arran over 8 years
      You won't be able to do that with Selenium. Selenium expects XPath queries to return physical DOM elements. Why doesn't a getAttribute('alt') not work?
  • arn-arn
    arn-arn over 8 years
    thanks Richard for the quick response... however, my case is that i have this application wherein user will just provide me the xpath and based on it the system will do the testing...but i guess there is no other way but do two calls...get the element first and then get the attribute

Related