How to Get Text of an Element in Selenium

Learn how to get text of an element in Selenium using Java and Python with this detailed guide.

How to Get Text of an Element in Selenium
Home Guide How to Get Text of an Element in Selenium

How to Get Text of an Element in Selenium

Have you ever used Selenium’s getText() and wondered why the value you expected didn’t appear?

I once spent hours trying to verify a simple button label, but Selenium kept returning empty or inconsistent results.

I changed locators, added waits—nothing worked reliably.

That’s when I realized the problem wasn’t Selenium but how different elements expose text.

Understanding when to use getText(), getAttribute(), or getProperty() changed everything.

Overview

getText() is a Selenium WebDriver method used to extract the visible text of a web element. It retrieves only what is rendered on the page, not hidden attributes or script-generated values.

How It Works (Crisp Points)

  • Reads visible text exactly as shown in the browser
  • Ignores hidden or CSS–invisible content
  • Depends on the DOM and browser rendering
  • Often used for validations in UI tests

Example

WebElement button = driver.findElement(By.id("signup-btn"));

String text = button.getText();

System.out.println(text); // Output: "Sign Up"

Important Considerations

  • Will not return text inside hidden elements
  • Dynamic content may require explicit waits
  • Frameworks like React/Angular may delay text rendering
  • Use getAttribute(“value”) for input fields instead of getText()
  • White spaces and formatting may vary across browsers

This article talks about how to use getText() in Selenium, its practical examples, limitations, and best practices to improve UI test reliability.

getText() Method in Selenium

The getText() method retrieves the visible text of a web element exactly as it appears in the browser. It’s commonly used to validate labels, headings, messages, and any UI content displayed to the user.

It works only with rendered text, so hidden or attribute-based values (like input fields) won’t be captured. In such cases, methods like getAttribute(“value”) are more appropriate.

According to Sarah Thomas, an expert in software testing, Selenium’s getText() method should be used only after the target element’s content has fully loaded and stabilized, ensuring text validations remain accurate and reliable on dynamic web pages.

Note: Using Selenium 3.141 in the below examples, the code might differ for Selenium 4 and would throw errors for Selenium 4 due to various changes in the new features offered by Selenium

Examples of Selenium getText() Method

The getText() method retrieves a web element’s visible (inner) text. It helps verify that the content displayed on the page matches expected values during automated tests.

This method works for elements like headings, paragraphs, buttons, alerts, and more.

Get Heading or Paragraph Text

You can use getText() to extract text from headings or paragraphs to ensure that users see the correct content.

python

heading = driver.find_element(By.TAG_NAME, 'h1').text

print("Heading text:", heading)

This code fetches the text of the first <h1> tag on the page.

Using getText() Method to Get Dropdown Text

getText() is helpful to get the selected option’s visible text in dropdown menus, which is critical for validating form inputs.

python

dropdown = driver.find_element(By.ID, 'dropdownId')

selected_option = dropdown.find_element(By.CSS_SELECTOR, 'option:checked').text

print("Selected dropdown option:", selected_option)

This snippet gets the currently selected option inside the dropdown with ID dropdownId.

Using getText() Method to Get Alert Text

When dealing with JavaScript alerts, getText() helps capture the alert’s message for validation or debugging.

python

alert = driver.switch_to.alert

alert_text = alert.text

print("Alert text:", alert_text)

This switches to the alert popup and prints its text content.

Accurately retrieving text across different browsers can be tricky, especially when UI rendering varies.

Platforms like BrowserStack Automate lets you validate getText() behavior on real browsers and devices, ensuring your text-based assertions work consistently everywhere.

Struggling with text mismatches in Selenium tests?

Text mismatches can break Selenium tests. Debug issues on real browsers with logs and recordings.

How to Get Text from Input Fields in Selenium

Input fields don’t expose their text as visible content, so getText() won’t work here. Instead, you retrieve the input’s value using the getAttribute(‘value’) method to get what the user has typed or what’s pre-filled.

python

input_field = driver.find_element(By.ID, 'inputFieldId')

input_text = input_field.get_attribute('value')

print("Input field text:", input_text)

This code fetches the current value inside the input field with ID inputFieldId.

How to Get All Text on a Page or From Multiple Elements in Selenium

Sometimes you want to extract all visible text on a page or from a list of elements. You can locate multiple elements and iterate over them to collect their text.

python

elements = driver.find_elements(By.CLASS_NAME, 'item-class')

for element in elements:

    print(element.text)

This example collects and prints text from all elements with the class item-class.

Using XPath and CSS Selectors to Retrieve Text in Selenium

XPath and CSS selectors help target specific elements precisely, which is useful when element locations are dynamic or complex. You can use these selectors with getText() to get the text content.

python

# Using XPath

text_xpath = driver.find_element(By.XPATH, '//div[@class="example"]/p').text

print("Text using XPath:", text_xpath)

# Using CSS Selector

text_css = driver.find_element(By.CSS_SELECTOR, 'div.example > p').text

print("Text using CSS Selector:", text_css)

Both snippets extract text from a paragraph <p> inside a div with class example, using different selector methods.

getText() Method Example: Verify the Get started free button

Here is an explanation of getText() in Selenium using an example. Assume, you want to verify the below Get started free Button WebElement by retrieving its innertext.

To do so, you need to first locate the element Get started free using Locators and then find the innertext of the element using getText() in Java and Python using the code snippets below:

Get Text of an Element in Selenium Example

Code Snippet to verify the Get started free button with Java

This Java example demonstrates how to locate and verify the text of the Get started free button using Selenium.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import io.github.bonigarcia.wdm.WebDriverManager;

import org.openqa.selenium.chrome.ChromeDriver;

import java.time.Duration;



public class Test{

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver = new ChromeDriver();

String url = "https:/browserstack.com”;

driver.get(url);

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));



// Locating the element 

WebElement e = driver.findElement(By.id("signupModalButton"));


//using getText method the retrieve the text of the element

System.out.println(e.getText());


driver.quit();

}

}

Test Result

Get started free

Run Selenium Tests on Real Devices

Code Snippet to verify the Get started free button with Python

This Python snippet shows how to find and assert the text of the Get started free button with Selenium WebDriver.

 from selenium import webdriver

 from webdriver_manager.chrome import ChromeDriverManager

 
 driver = webdriver.Chrome(ChromeDriverManager().install())

driver.get("https:/browserstack.com”)


# text method is used in python to retrieve the text of WebElement

 print(driver.find_element_by_id("signupModalButton").text)
  

driver.close()

Test Result

Get started free

Do you know findElement and findElements are different in Selenium? Read to know the difference.

Trouble verifying text across browsers?

Incorrect text rendering can break validations. Test on real browsers for reliable results.

How to test the above getText() method example for Cross Browser Compatibility

With the availability of different devices and browsers in the market, it becomes necessary to deliver a consistent and seamless user experience across different browsers and devices. Hence, it is essential to test cross browser compatibility for every feature test case. This section demonstrates how to test cross browser compatibility of getText() test case using BrowserStack Automate.

BrowserStack real device cloud allows you to access 3500+ real devices and browsers to test your application and get more accurate results by testing under real user conditions. It makes debugging easier by providing text logs, console logs, screenshots, and video logs that can be shared with team using Integrations like Trello and JIRA.

Run Selenium Tests for Free

Here is an example by executing above getText() method example code on a macOS device with a browser as Firefox by setting desired capabilities in Selenium Webdriver.

Note: Desired Capabilities are depreciated in Selenium 4, so you can use the below code only when using Selenium 3. In this guide, we have used Selenium 3.141

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.Platform;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.remote.Augmenter;

import org.openqa.selenium.remote.DesiredCapabilities;

import org.openqa.selenium.remote.RemoteWebDriver;

import org.testng.Assert;

import java.net.URL;

import java.time.Duration;

import org.testng.annotations.Test;



public class BSTests {

public WebDriver driver;

public static final String USERNAME = "your_username";

public static final String AUTOMATE_KEY = "your_access_key";

public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY +    "@hub.browserstack.com/wd/hub";

@Test

public void BWTest() throws Exception {

DesiredCapabilities capability = new DesiredCapabilities();

capability.setPlatform(Platform.MAC);

capability.setBrowserName("firefox");

capability.setVersion("38");

capability.setCapability("browserstack.debug","true");

capability.setCapability("build_name","Test to verify text of webelement");

// Create object of driver. We execute scripts remotely. So we use RemoteWebDriver

//There are many constructors to remotewebdriver

//To pass URL object and Capabilities object, use the below mentioned constructor

//RemoteWebDriver(URL remoteAddress, Capabilities desiredCapabilities)

driver = new RemoteWebDriver(new URL(URL),capability);

// to open url

driver.get("https://www.browserstack.com/");

//Implicit wait for 30 seconds

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));



// Locating the element 

WebElement e = driver.findElement(By.id("signupModalButton"));

 String actualElementText = e.getText();

//using getText method the retrieve the text of the element

String expectedElementText = "Get started free";

 //Assert to verify the actual and expected values

Assert.assertEquals(actualElementText, expectedElementText,"Expected and Actual are not same");

driver.quit();

}

}

Test Result

The above example shows how to test on multiple real devices using BrowserStack. In this example, we have executed our test on macOS device, firefox browser, and browser version “38” by setting the desired capabilities option given by BrowserStack.

Similarly, you can test on multiple real-time devices and browsers parallelly on BrowserStack for testing cross browser compatibility. All you need is to Sign up with BrowserStack and it will generate a username and access key for you and you are all set to get started.

Below are a few screenshots of execution details of the above test on BrowserStack.

Executing Selenium Get Text of an Element Test on BrowserStack

Text Logs of how our execution progressed

Text logs how execution progressed

Desired capabilities set by the user

Setting Desired Capabilities for Get Text of an Element in Selenium example

getAttribute() vs getProperty() vs getText() in Selenium

Here’s a comparison of the three commonly used methods in Selenium for retrieving element values and content.

MethodDescriptionUse Case Example
getAttribute()Returns the value of the specified HTML attributeelement.get_attribute(“href”)
getProperty()Returns the current value of a DOM property (runtime JS state)element.get_property(“value”)
getText()Returns the visible text of the elementelement.get_text()

Example Comparison:

# Assume <input type="text" value="Hello" />

input_field = driver.find_element(By.ID, "name")

print("Attribute value:", input_field.get_attribute("value"))   # "Hello"

print("Property value:", input_field.get_property("value"))     # "Hello" (updated by JS if changed)
  • Use getAttribute() for static HTML values.
  • Use getProperty() for dynamic values updated by JavaScript.
  • Use getText() for visible text between opening and closing tags.

Limitations While Using getText() Method in Selenium

While getText() is useful, it has a few limitations that can affect reliability in tests:

  • It only retrieves visible text; hidden elements or content rendered via pseudo-elements won’t be captured.
  • Whitespace and formatting may vary across browsers, affecting string comparison.
  • It may fail with dynamic content updated by JavaScript unless waits are properly handled.

Best Practices for getText() Method in Selenium

To make the most of getText() in your automation scripts, follow these tips:

  • Use explicit waits (WebDriverWait) to ensure text is fully loaded before retrieval.
  • Normalize and trim the output before performing assertions to handle formatting inconsistencies.
  • Prefer stable locators (like IDs or data attributes) to avoid flakiness when selecting elements.
  • Combine with logging or screenshot capture for better debugging during test failures.

Talk to an Expert

Scale Your Selenium getText() Tests with BrowserStack Automate

Text retrieval can behave differently across browsers, devices, and rendering engines. UI frameworks, whitespace handling, and dynamic content all influence what getText() returns, making cross-browser validation essential.

BrowserStack Automate helps you scale these tests by providing:

  • Access to 3500+ real browsers and devices to verify text exactly as users see it
  • Parallel test execution to accelerate large suites with multiple getText() validations
  • Accurate rendering environments that eliminate flakiness caused by emulators or inconsistent setups
  • Detailed debugging tools such as screenshots, videos, and console logs to troubleshoot text mismatches quickly

With BrowserStack Automate, teams can confidently validate UI text across real-user conditions and ensure consistent, reliable results at scale.

Try BrowserStack Now

Conclusion

Selenium getText() method is very useful for operations like verifying messages, errors, asserting WebElements, and many more. It can also be used to retrieve the entire text body of a webpage. With BrowserStack real device cloud, you can test on 3500+ real device browser combinations of our choice which helps to test under real user conditions for better user experience, improves accuracy, and gives a seamless experience across different platforms, browsers, and devices.

Tags
Automated UI Testing Selenium Selenium Webdriver

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord