Selenium – How to get the value of an attribute using XPath

seleniumselenium-webdriverxpath

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.

Best Answer

You can use the getAttribute() method.

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