Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

How can we get text on a web element using Selenium?

You can get the text of a web element in Selenium by locating the element and calling the getText() method of the WebElement interface. It returns the visible, rendered text between the element's tags, including the text of its child elements, with leading and trailing whitespace trimmed. For input fields or hidden text, use getAttribute() instead.

Understanding the getText() Method in Selenium

In Selenium, getText() reads only what is actually rendered on screen, not hidden attributes or script-generated values. This makes it the go-to method for validating labels, headings, success messages, and any UI content shown to the user. It returns the combined text of the element and all of its descendants, and it strips surrounding whitespace so your assertions stay clean.

Because getText() depends on visibility, it works best when the element is present and visible. On dynamic pages it is good practice to wait for the element before reading its text, which avoids intermittent empty results.

Getting Element Text with getText()

Locate the element with any locator such as ID, CSS selector, or XPath, then call getText() on the returned WebElement. The Java example below reads a heading and asserts on it.

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

// Assuming 'driver' is an initialized WebDriver instance
WebElement heading = driver.findElement(By.cssSelector("#welcome-banner"));
String text = heading.getText();

System.out.println("Element text: " + text);

// Use it in an assertion
if (text.equals("Welcome back!")) {
    System.out.println("Banner text is correct");
}

Waiting for the Element Before Reading Text

If content loads asynchronously, calling getText() too early returns an empty string. Pair it with an explicit wait so Selenium reads the text only after the element is visible.

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.time.Duration;

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement message = wait.until(
    ExpectedConditions.visibilityOfElementLocated(By.id("status-message"))
);
System.out.println("Status: " + message.getText());

For more on wait strategies, see the types of waits available in WebDriver.

getText() vs getAttribute(): When to Use Each

These two methods retrieve different things, and mixing them up is a common source of empty or wrong results:

  • getText(): Returns the visible inner text of an element, for example the label on a button or the words in a paragraph.
  • getAttribute("value"): Returns what a user typed into an input or textarea, since that content lives in the value attribute, not as visible text.
  • getAttribute("innerText") or "textContent": Returns text even when it is hidden by CSS, unlike getText().
  • getAttribute("href"), "placeholder", etc.: Returns any other HTML attribute value you need.

To locate elements by their text in the first place, see the guide on how to find an element by text in Selenium.

Getting Text in Python

In the Python bindings, text is exposed as a property named text rather than a method call, but the behavior matches getText().

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://www.example.com")

element = driver.find_element(By.CSS_SELECTOR, "#some-element")
text = element.text
print(text)

driver.quit()

Common Mistakes and Troubleshooting

  • Empty string on input fields: getText() returns nothing for form inputs. Use getAttribute("value") to read typed content.
  • Reading text before it loads: A getText() call that runs before the element renders returns empty. Add an explicit wait for visibility.
  • Text hidden by CSS: getText() ignores content with display:none. Use getAttribute("textContent") to retrieve it.
  • Unexpected child text: getText() merges child element text. Use a JavaScriptExecutor if you need only the parent's own text.
  • Stale element after navigation: Re-locate the element after the DOM changes to avoid a StaleElementReferenceException.

Validating Text Across Real Browsers and Devices

The exact text a user sees can vary with locale, font rendering, and responsive layouts across browsers, so text assertions should be checked on more than one local environment. TestMu AI lets you run your Selenium suites on a cloud of 3000+ real browsers and operating systems, so a getText() assertion that passes locally is confirmed on the same browsers and devices your users have. Extending your automation testing and cross-browser testing this way catches localization and rendering differences a single-browser run would miss.

Conclusion

Getting text from a web element in Selenium comes down to choosing the right method: use getText() for visible, rendered text, and getAttribute() for input values, hidden text, or other attributes. Wait for the element to be visible before reading it, watch out for child-element text and stale references, and validate your assertions across real browsers. To build on this, learn how to check whether an element is displayed.

Frequently Asked Questions

What is the difference between getText() and getAttribute() in Selenium?

getText() returns the visible, rendered text between an element's tags. getAttribute() returns the value of a specific HTML attribute, such as value, href, or placeholder. For input fields, use getAttribute("value") because the typed text is stored in the value attribute, not as visible text.

Why does getText() return an empty string?

getText() only returns text that is visually rendered. If the element is hidden by CSS such as display:none or visibility:hidden, or has not finished loading, it returns an empty string. Use an explicit wait for visibility, or read the value attribute for hidden content.

How do you get text from an input field in Selenium?

Text typed into an input or textarea lives in the value attribute, not as inner text, so getText() usually returns empty. Use element.getAttribute("value") to read exactly what the user entered into a form field.

How do you get text excluding child element text?

getText() returns the combined text of an element and all its children. To get only the parent's own text, use a JavaScriptExecutor to read the first text node, or extract the child text separately and remove it from the full string.

Does getText() include leading and trailing spaces?

No. getText() automatically trims leading and trailing whitespace and returns the visible text as rendered. If you need the raw or untrimmed content, use getAttribute("innerText") or getAttribute("textContent") instead.

How do you get text in Selenium with Python?

In Python bindings, text is exposed as a property rather than a method. Locate the element and read element.text, which behaves like getText() in Java and returns the visible, trimmed text of the element and its children.

Related Questions

Test Your Website on 3000+ Browsers

Get 100 minutes of automation test minutes FREE!!

Test Now...

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

...

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests