How to get attribute of element from Selenium?

We can get the attribute of element in Selenium webdriver. The getAttribute() method is used to obtain the value of an attribute in an html document. In an html code, attribute and its value appear as a key value pair.

Some of the commonly known html attributes are disabled, alt, id, href, style, title and src. The value of the attribute that we want to fetch is passed as an argument to the method.

Let us consider an html code, for which we shall obtain the src attribute. The value of the src attribute should be /about/images/logo.png.


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;

public class GetSrcAttribute{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      String u = ""driver.get(u);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement t=driver.findElement(By.xpath("//img[@class='tp-logo']"));
      // get src attribute with getAttribute()
      System.out.println("Src attribute is : " + t.getAttribute("src"));