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.

Example

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

public class GetSrcAttribute{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String u = "https://www.tutorialspoint.com/about/about_careers.htm"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"));
      driver.close();
   }
}

Output

Updated on: 18-Sep-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements