This guide will show you how to use Selenium get attribute to extract the value of any HTML attribute from a web element. You’ll learn how
getAttribute()
works, when to use it, and how it differs from other methods likegetText()
with real-world examples.
Selenium getAttribute() method
- getAttribute() method is part of WebElement interface which extends SearchContext and TakesScreenshot interfaces.
- getAttribute() method is used to get value of that specific attribute of an element.
- It will return value of attribute if attribute found.
- It will return empty string if attribute not found.
- Syntax for getAttribute() method : driver.findElement(By.Element_locator).getAttribute(Attribute_name);
getAttribute() method example
In above given image, element Grand Parent1 have total 3 attributes id, name and type. We will locate that element by id and then try to get it’s name and type attribute’s values.
package testPackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClearExample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://only-testing-blog.blogspot.com/2022/11/relationship.html");
//Find and locate textbox element by id.
WebElement gp = driver.findElement(By.id("gparent_1"));
//Get value of name attribute and print it in console.
String name_Attr = gp.getAttribute("name");
System.out.println("Name attribute value = "+name_Attr);
//Get value of type attribute and print it in console.
String type_Attr = gp.getAttribute("type");
System.out.println("Type attribute value = "+type_Attr);
//Get value of class attribute and print it in console.
String class_Attr = gp.getAttribute("class");
System.out.println("class attribute value = "+class_Attr);
}
}
In above given example, We located element by id. Then get attribute values of name, type, class and then print it in console. It will return values of name and type attributes. Value of class attribute will be null because that attribute is not available on element.