In Selenium automation, we often need to work with HTML attributes of web elements. Selenium provides the getAttribute() method, which allows us to fetch the value of any HTML tag attribute directly.
Using getAttribute(), we can:
- Retrieve attribute values such as
id,name,href,value,class,placeholder, etc. - Compare the returned values with expected results using assertions for validation checks.
- Reuse the logic by creating utility methods for
getAttribute()to improve code maintainability.
To demonstrate this, below is an example Selenium script in Java. This script shows two different ways of fetching attribute values:
- By passing a WebElement directly (overloaded method).
- By passing a locator (By).
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class AttributeExample {
WebDriver driver;
@BeforeClass
public void setup() {
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://example.com"); // Replace with your URL
}
@Test
public void fetchAttribute() {
// Locate element
By locator = By.id("fruit-color");
// Get attribute value
String value = getAttributeValue(locator, "value");
System.out.println("Attribute value: " + value);
}
// ✅ Reusable method with By locator
public String getAttributeValue(By locator, String attributeName) {
WebElement element = driver.findElement(locator);
return element.getAttribute(attributeName);
}
// ✅ Overloaded method (if you already have WebElement)
public String getAttributeValue(WebElement element, String attributeName) {
return element.getAttribute(attributeName);
}
@AfterClass
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
}