We get text and attributes from web elements to check if the page shows the right information or has the correct settings.
0
0
Getting text and attributes in Selenium Java
Introduction
To verify a button label says 'Submit' before clicking it.
To check if a link has the correct URL in its href attribute.
To confirm a message on the page matches expected text after an action.
To read the value inside a text box or input field.
To ensure an image has the right alt text for accessibility.
Syntax
Selenium Java
String text = driver.findElement(By.locator).getText();
String attributeValue = driver.findElement(By.locator).getAttribute("attributeName");getText() returns the visible text inside an element.
getAttribute() returns the value of the given attribute, like href, src, or value.
Examples
Gets the visible text from a button with id 'submitBtn'.
Selenium Java
String buttonText = driver.findElement(By.id("submitBtn")).getText();Gets the URL from the href attribute of a link with class 'home-link'.
Selenium Java
String linkHref = driver.findElement(By.cssSelector("a.home-link")).getAttribute("href");
Gets the current value typed inside an input box named 'username'.
Selenium Java
String inputValue = driver.findElement(By.name("username")).getAttribute("value");
Sample Program
This test opens example.com, gets the main heading text and a link's href attribute, prints them, and checks if they match expected values.
Selenium Java
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class GetTextAndAttributesTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com"); WebElement heading = driver.findElement(By.tagName("h1")); String headingText = heading.getText(); WebElement link = driver.findElement(By.cssSelector("p a")); String linkHref = link.getAttribute("href"); System.out.println("Heading text: " + headingText); System.out.println("Link href: " + linkHref); assert headingText.equals("Example Domain") : "Heading text does not match!"; assert linkHref.startsWith("https://") : "Link href is not a valid URL!"; System.out.println("All assertions passed."); } finally { driver.quit(); } } }
OutputSuccess
Important Notes
Always wait for elements to be visible before getting text or attributes to avoid errors.
getText() returns visible text only, not hidden or attribute text.
getAttribute() returns null if the attribute does not exist on the element.
Summary
Use getText() to read visible text from elements.
Use getAttribute() to read any attribute value from elements.
Check the values you get to confirm the page shows what you expect.