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
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. 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) Example Important Considerations This clause talks about how to use getText () in Selenium, its practical exemplar, limitations, and best drill to improve UI exam reliability. 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 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: You can usegetText()to extract text from header or paragraph to ensure that users see the correct content. python This code fetches the text of the first& lt; h1 & gt;tag on the page. getText()is helpful to get the selected option & # 8217; s seeable text in dropdown card, which is critical for validating form inputs. python This snippet gets the currently take option inside the dropdown with IDdropdownId. When dealing with JavaScript alerts, getText () aid capture the alert ’ s content for proof or debugging. Also Read: python 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. 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 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: 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 This example collects and prints text from all elements with the classitem-class. Read More: 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 Both snippets extract text from a paragraph<p>inside a div with stratumexample, employ different selector methods. 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: This Java exemplar manifest how to situate and verify the text of the Get started free push using Selenium. Test Result Get started free This Python snip shows how to happen and aver the textbook of theGet started freepush with. Test Result Get commence free Do you cognise?Read to cognize the difference. 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 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 Here ’ s a comparison of the three usually habituate method in Selenium for retrieving element values and content. Example Comparison: Also Read: While getText () is useful, it has a few limitation that can regard reliability in tests: Learn More: To make the most of getText () in your automation scripts, postdate these tips: 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: With BrowserStack Automate, teams can confidently validate UI text across and ensure consistent, reliable results at scale. 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. 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 # Ask-and-Contributeabout this matter with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.Related Product
How to Get Text of an Element in Selenium
Overview
WebElement button = driver.findElement (By.id (`` signup-btn '')); String text = button.getText (); System.out.println (text); // Output: `` Sign Up ''
getText () Method in Selenium
Examples of Selenium getText () Method
Get Heading or Paragraph Text
head = driver.find_element (By.TAG_NAME, 'h1 ') .text print (`` Heading textbook: '', heading)
Using getText () Method to Get Dropdown Text
dropdown = driver.find_element (By.ID, 'dropdownId ') selected_option = dropdown.find_element (By.CSS_SELECTOR, 'option: checked ') .text print (`` Selected dropdown option: '', selected_option)
Using getText () Method to Get Alert Text
alert = driver.switch_to.alert alert_text = alert.text print (`` Alert text: '', alert_text)
Struggling with text mismatches in Selenium tests?
How to Get Text from Input Fields in Selenium
input_field = driver.find_element (By.ID, 'inputFieldId ') input_text = input_field.get_attribute ('value ') mark (`` Input field text: '', input_text)How to Get All Text on a Page or From Multiple Elements in Selenium
elements = driver.find_elements (By.CLASS_NAME, 'item-class ') for element in element: mark (element.text)
Using XPath and CSS Selectors to Retrieve Text in Selenium
# 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)
getText () Method Example: Verify the Get started free push
Code Snippet to verify the Get started free button with Java
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 ();}}Code Snippet to verify the Get started free button with Python
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 ()
Trouble verify textbook across browsers?
How to test the above getText () method example for Cross Browser Compatibility
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 ();}}getAttribute () vs getProperty () vs getText () in Selenium
Method Description Use Case Example Returns the value of the qualify HTML attribute element.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 factor element.get_text () # 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)
Limitations While Using getText () Method in Selenium
Best Practices for getText () Method in Selenium
Scale Your Selenium getText () Tests with BrowserStack Automate
Conclusion
FAQs
Related Guides
Automate This With SUSA
Test Your App Autonomously