Getting Attribute Value Using Selenium
Use element.getAttribute("attributeName") to retrieve the value of any HTML attribute.
Basic usage:
Java
WebElement element = driver.findElement(By.id("myInput"));
String value = element.getAttribute("value"); // Get input field value
Common attribute examples:
Java
WebElement input = driver.findElement(By.name("username"));
// Get input value
String inputValue = input.getAttribute("value");
// Get placeholder text
String placeholder = input.getAttribute("placeholder");
// Get class name
String className = input.getAttribute("class");
// Get id
String id = input.getAttribute("id");
// Check if disabled
String disabled = input.getAttribute("disabled"); // "true" or null
// Get type (text, password, checkbox, etc.)
String type = input.getAttribute("type");
Link href attribute:
Java
WebElement link = driver.findElement(By.linkText("Home"));
String href = link.getAttribute("href");
System.out.println("Link URL: " + href);
Image src attribute:
Java
WebElement img = driver.findElement(By.tagName("img"));
String src = img.getAttribute("src");
String alt = img.getAttribute("alt");
System.out.println("Image source: " + src);
Tooltip via title attribute:
Java
WebElement helpIcon = driver.findElement(By.id("helpIcon"));
String tooltip = helpIcon.getAttribute("title");
Assert.assertEquals(tooltip, "Click for help");
Custom data attributes:
Java
// For <div data-user-id="123" data-role="admin">
WebElement card = driver.findElement(By.className("user-card"));
String userId = card.getAttribute("data-user-id"); // "123"
String role = card.getAttribute("data-role"); // "admin"
Full test example:
Java
@Test
public void verifyAttributes() {
driver.get("https://example.com/form");
WebElement emailInput = driver.findElement(By.id("email"));
Assert.assertEquals(emailInput.getAttribute("type"), "email");
Assert.assertEquals(emailInput.getAttribute("placeholder"), "Enter your email");
Assert.assertNull(emailInput.getAttribute("disabled")); // Not disabled
}
getAttribute vs getCssValue:
Java
// getAttribute — HTML attributes
element.getAttribute("class"); // "btn btn-primary"
element.getAttribute("href"); // "https://example.com"
// getCssValue — CSS style properties
element.getCssValue("color"); // "rgba(255, 0, 0, 1)"
element.getCssValue("font-size"); // "16px"
Key answer: Use element.getAttribute(value) to get any HTML attribute value from a web element.
