In Selenium automation with Java, we frequently use both getText() and getAttribute() methods. Although they may seem similar, they serve different purposes when extracting information from web elements.
🔹 1. getText() in Selenium
- The
getText()method is used to fetch the visible inner text of a web element. - It only returns the text that is displayed between the opening and closing tags of an element.
- Commonly used for fetching text from elements like
<span>,<div>,<p>,<a>etc.
✅ Example – Using getText()
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class GetTextExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get(“https://example.com”);
// Example: Fetch visible text from a link
WebElement link = driver.findElement(By.tagName("a"));
String linkText = link.getText();
System.out.println("Link Text: " + linkText);
driver.quit();
}
}
🔹 2. getAttribute() in Selenium
- The
getAttribute()method is used to fetch the value of an HTML attribute of a web element. - It can be used to extract attributes like
id,href,value,class,placeholder, etc. - Works well with input elements, buttons, and links.
✅ Example – Using getAttribute()
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class GetAttributeExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get(“https://example.com”);
// Example: Fetch the "href" attribute of a link
WebElement link = driver.findElement(By.tagName("a"));
String hrefValue = link.getAttribute("href");
System.out.println("Link Href: " + hrefValue);
// Example: Fetch the "placeholder" attribute of input field
WebElement input = driver.findElement(By.id("username"));
String placeholder = input.getAttribute("placeholder");
System.out.println("Input Placeholder: " + placeholder);
driver.quit();
}
}
🔑 Key Difference Between getText() and getAttribute()
| Method | What It Returns | Example Usage |
|---|---|---|
getText() | Visible inner text between HTML tags | link.getText() → "Login" |
getAttribute("value") | Value of a given attribute | input.getAttribute("placeholder") → "Enter username" |
getAttribute("href") | URL defined in anchor tag | link.getAttribute("href") → "https://example.com/login" |
✅ Quick Tip
- Use
getText()when validating visible text on the page. - Use
getAttribute()when validating hidden attribute values likehref,value, orplaceholder.