arn-arn
arn-arn

Reputation: 1377

How to get the value of an attribute using XPath

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.

Upvotes: 12

Views: 50248

Answers (4)

hex
hex

Reputation: 763

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.

Upvotes: 1

polkovnikov.ph
polkovnikov.ph

Reputation: 6632

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');
        });
  `);

Upvotes: 1

JerodG
JerodG

Reputation: 1334

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

Upvotes: 3

Richard
Richard

Reputation: 9019

You can use the getAttribute() method.

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

Upvotes: 18

Related Questions