Selenium’s getText() method is essential for validating visible text in automated UI tests.
Overview
What is getText() Method in Selenium?
The getText() method retrieves the visible (rendered) text from a web element.
Use Cases of getText() Method in Selenium:
- Verifying button labels and headings
- Capturing success or error messages
- Extracting text from alerts or popups
- Validating dropdown selections
- Asserting dynamic content on pages
Best Practices of getText() Method:
- Wait for text to fully load
- Trim and normalize extracted text
- Use stable, accurate locators
- Avoid comparing long multiline strings
- Combine with screenshots for debugging
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
This method helps retrieve the text, which is basically the innertext of a WebElement. getText() method returns string as a result. It removes the whitespaces if present in the front and back of the string.
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.
Also Read: findElement and findElements in Selenium
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.
Must Read: How to handle Alerts & Popups in Selenium
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.
Must Read: How to Find Elements by ID in Selenium
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.
Read More: Core Selenium WebElement Commands
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:
Learn More: Architecture of Selenium WebDriver
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.
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.
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.
Text Logs of how our execution progressed
Desired capabilities set by the user
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.
Method | Description | Use Case Example |
---|---|---|
getAttribute() | Returns the value of the specified HTML attribute | element.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 element | element.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.
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.