Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 806
arn-arn Avatar asked Apr 30 '14 17:04

arn-arn


2 Answers

You can use the getAttribute() method.

driver.findElement(By.xpath("//div[@class='firstdiv']")).getAttribute("alt");
like image 112
Richard Avatar answered Nov 06 '22 19:11

Richard


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");
        }
like image 24
JerodG Avatar answered Nov 06 '22 20:11

JerodG