How to Get Text of an Element in Selenium

Related Product On This Page getText () Method in SeleniumJune 09, 2026 · 11 min read · Tool Comparison

Related Product

How to Get Text of an Element in Selenium

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

I formerly drop hours trying to verify a unproblematic push label, butSeleniumkept returningempty or inconsistent result.

I changed locators, added waits—nothing worked faithfully.

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

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

Overview

getText () is a Selenium WebDriver method utilise to extract thevisible textof a web element. It retrieves only what is rendered on the page, not secret property or script-generated values.

How It Works (Crisp Points)

  • Reads visibletext exactly as shown in the browser
  • Ignores enshroud or CSS–invisible message
  • 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 (& # 8220; value & # 8221;)for stimulant fields instead ofgetText()
  • White spaces and formatting may vary across browsers

This clause talks about how to use getText () in Selenium, its practical exemplar, limitations, and best drill to improve UI exam reliability.

getText () Method in Selenium

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

It act only withrendered text, so hidden or attribute-based value (like input field) won ’ t be capture. In such cases, methods like getAttribute (& # 8220; value & # 8221;) are more appropriate.

According toSarah Thomas,an expert in software examination, Selenium ’ s getText () method should be used only after the target element ’ s substance has fully lade and stabilized, ensuring text validations stay accurate and reliable on dynamic web pages.

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

Examples of Selenium getText () Method

The getText () method recover a web element & # 8217; s visible (intimate) text. It helps control that the substance exhibit on the page match await values during machine-driven test.

This method works for elements like headings, paragraph, push, alerts, and more.

Also Read:

Get Heading or Paragraph Text

You can usegetText()to extract text from header or paragraph to ensure that users see the correct content.

python

head = driver.find_element (By.TAG_NAME, 'h1 ') .text print (`` Heading textbook: '', heading)

This code fetches the text of the first& lt; h1 & gt;tag on the page.

Using getText () Method to Get Dropdown Text

getText()is helpful to get the selected option & # 8217; s seeable text in dropdown card, 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 take option inside the dropdown with IDdropdownId.

Using getText () Method to Get Alert Text

When dealing with JavaScript alerts, getText () aid capture the alert ’ s content for proof or debugging.

Also Read:

python

alert = driver.switch_to.alert alert_text = alert.text print (`` Alert text: '', alert_text)

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

Must Read:

Accurately retrieving text across different browser can be tricky, particularly when UI provide varies.

Platforms like Lashkar-e-Taiba you validate getText () behavior on real browser and device, ensuring your text-based assertions work systematically everywhere.

Struggling with text mismatches in Selenium tests?

Text mismatches can break Selenium tests. Debug issues on existent browser with logs and recordings.

How to Get Text from Input Fields in Selenium

Input battlefield don ’ t expose their textbook as visible content, sogetText()won ’ t work here. Instead, you find the stimulus ’ s value using thegetAttribute (& # 8216; value & # 8217;)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 ') mark (`` Input field text: '', input_text)

This codification fetches the current value inside the input battleground with IDinputFieldId.

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

Must Read:

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 tilt of elements. You can site multiple elements and iterate over them to collect their textbook.

python

elements = driver.find_elements (By.CLASS_NAME, 'item-class ') for element in element: mark (element.text)

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

Read More:

Using XPath and CSS Selectors to Retrieve Text in Selenium

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

python

# Using XPath text_xpath = driver.find_element (By.XPATH, '//div [@ class= '' example ''] /p ') .text mark (`` Text using XPath: '', text_xpath) # Using CSS Selector text_css = driver.find_element (By.CSS_SELECTOR, 'div.example & gt; p ') .text print (`` Text apply CSS Selector: '', text_css)

Both snippets extract text from a paragraph<p>inside a div with stratumexample, employ different selector methods.

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

Here is an explanation ofgetText()in Selenium habituate an example. Assume, you require to control the below Get started gratis Button WebElement by recover its innertext.

To do so, you need to first site the element Get part costless use Locators and so find the innertext of the factor employgetText() in Java and Python using the code snippets below:

Learn More:

Code Snippet to verify the Get started free button with Java

This Java exemplar manifest how to situate and verify the text of the Get started free push using Selenium.

importation org.openqa.selenium.By; meaning org.openqa.selenium.WebDriver; significance org.openqa.selenium.WebElement; signification io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.chrome.ChromeDriver; import java.time.Duration; public class Test {public static vacuum primary (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 schoolbook of the element System.out.println (e.getText ()); driver.quit ();}}

Test Result

Get started free

Code Snippet to verify the Get started free button with Python

This Python snip shows how to happen and aver the textbook of theGet started freepush with.

from selenium significance 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 textbook of WebElement print (driver.find_element_by_id (`` signupModalButton '') .text) driver.close ()

Test Result

Get commence free

Do you cognise?Read to cognize the difference.

Trouble verify textbook across browsers?

Incorrect text render can break validation. Test on real browsers for reliable results.

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

With the availableness of different devices and browsers in the marketplace, it becomes necessary to deliver a consistent and unseamed 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 ofgetText()test case using.

BrowserStack allows you to access 3500+ real devices and browsers to test your application and get more precise results by testing under. It makes debugging leisurely by providing text logs, console logs, screenshots, and video logs that can be shared with team using.

Here is an example by executing abovegetText()method example codification on a macOS device with a browser as Firefox by fix.

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

signification java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.Platform; importee 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; meaning 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 terminal String AUTOMATE_KEY = `` your_access_key ''; public static last String URL = `` https: // '' + USERNAME + ``: '' + AUTOMATE_KEY + `` @ hub.browserstack.com/wd/hub ''; @ Test public void BWTest () throws Exception {DesiredCapabilities potentiality = new DesiredCapabilities (); capability.setPlatform (Platform.MAC); capability.setBrowserName (`` firefox ''); capability.setVersion (`` 38 ''); capability.setCapability (`` browserstack.debug '', '' true ''); capability.setCapability (`` build_name '', '' Test to control schoolbook of webelement ''); // Create target of driver. We execute scripts remotely. So we use RemoteWebDriver //There are many constructor to remotewebdriver //To pass URL target and Capabilities object, use the below mentioned builder //RemoteWebDriver (URL remoteAddress, Capabilities desiredCapabilities) driver = new RemoteWebDriver (new URL (URL), capability); // to open url driver.get (`` https: //www.browserstack.com/ ''); //Implicit await 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 ingredient String expectedElementText = `` Get depart free ''; //Assert to verify the actual and expect value Assert.assertEquals (actualElementText, expectedElementText, '' Expected and Actual are not like ''); driver.quit ();}}

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

Similarly, you can test on multiple real-time devices and browser parallelly on BrowserStack for test mark browser compatibility. All you necessitate is to and it will give a username and access key for you and you are all set to get commence.

Read More:

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

Text Logs of how our executing progressed

Desired capabilities set by the exploiter

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

Here ’ s a comparison of the three usually habituate method in Selenium for retrieving element values and content.

MethodDescriptionUse Case Example
Returns the value of the qualify HTML attributeelement.get_attribute (& # 8220; href & # 8221;)
getProperty ()Returns the current value of a DOM holding (runtime JS state)element.get_property (& # 8220; value & # 8221;)
getText()Returns the visible text of the factorelement.get_text ()

Example Comparison:

# Assume & lt; input type= '' text '' value= '' Hello '' / & gt; 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 modify)
  • Use getAttribute ()for static HTML values.
  • Use getProperty ()for dynamic values updated by JavaScript.
  • Use getText()for visible text between opening and closing tags.

Also Read:

Limitations While Using getText () Method in Selenium

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

  • It only recover visible text; concealed elements or content rendered via pseudo-elements won ’ t be beguile.
  • Whitespace and formatting may vary across browser, affecting string comparison.
  • It may fail with active content updated by JavaScript unless waits are properly manage.

Learn More:

Best Practices for getText () Method in Selenium

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

  • Use (WebDriverWait) to ensure schoolbook is full loaded before recovery.
  • Normalize and trim the output before perform assertions to handle initialise repugnance.
  • Prefer stable (like IDs or data attributes) to deflect flakiness when take elements.
  • Combine with logging or screenshot capture for best debugging during examination failures.

Talk to an Expert

Scale Your Selenium getText () Tests with BrowserStack Automate

Text retrieval can do differently across browsers, devices, and supply engines. UI frameworks, whitespace treatment, and dynamical substance all influence what getText () returns, making cross-browser substantiation essential.

BrowserStack Automate helps you scale these tests by providing:

  • Access to 3500+ real browser and devicesto verify text exactly as users see it
  • executionto speed large suites with multiple getText () validations
  • Accurate interpreting environmentsthat eliminate flakiness get by emulators or inconsistent setup
  • Detailed debugging toolssuch as screenshots, videos, and console logs to troubleshoot text mismatches apace

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

Conclusion

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

Tags

FAQs

getText () returns simply seeable text. If the constituent ’ s content is hidden, inside an input battleground, or rendered dynamically before it becomes visible, the method returns an empty-bellied string. Using wait or getAttribute (& # 8220; value & # 8221;) may be required.

getText () regain visible, rendered text on the page, while getAttribute () reads the value of an HTML dimension (like & # 8220; value & # 8221;, & # 8220; placeholder & # 8221;, or & # 8220; title & # 8221;). Input field typically necessitate getAttribute (& # 8220; value & # 8221;).

Browsers may handle whitespace, formatting, or dynamic rendering differently. As a result, getText () yield can change. Validating textbook on real browser aid ensure consistent results.

On This Page

48,000+ Views

# Ask-and-Contributeabout this matter with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free