"Automation is not about replacing jobs; it's about empowering people to do more meaningful work." — Unknown

getText()

Estimated reading: 5 minutes 23 views

Overview

The getText() method in Selenium WebDriver is used to retrieve the visible text of a web element. This method extracts and returns the inner text of the element, excluding any HTML tags, attributes, or child elements that are not visible to the user. The getText() method is essential for verifying the content of elements, such as paragraphs, buttons, labels, and other text-containing elements, during automated tests.

This method is commonly used to ensure that the displayed text on a page matches the expected content, which is vital for content validation, form field testing, and testing dynamic page content.

Syntax

				
					String text = element.getText();
				
			
  • element: The WebElement from which the text will be extracted.
  • getText(): Returns the visible text of the element as a String.

Usage

The getText() method is widely used to capture the content of elements, especially for:

  1. Verifying Text Content: Ensure that an element contains the expected text, which is commonly used for testing labels, buttons, or dynamic content.

				
					WebElement header = driver.findElement(By.id("header"));
String headerText = header.getText();
System.out.println("Header text: " + headerText);
				
			

2. Validating Dynamic Content: In dynamic applications, you may need to confirm that the displayed text updates after an action, such as clicking a button or submitting a form.

				
					WebElement successMessage = driver.findElement(By.id("success-message"));
String message = successMessage.getText();
if (message.equals("Form submitted successfully")) {
    System.out.println("Success message is correct.");
}
				
			

3. Text Extraction from Non-input Elements: The getText() method is useful for extracting text from non-input elements like headings, paragraphs, lists, and other HTML elements.

				
					WebElement paragraph = driver.findElement(By.id("intro"));
String paragraphText = paragraph.getText();
System.out.println("Paragraph text: " + paragraphText);
				
			

4. Testing Web Elements After User Interactions: After performing an action (like clicking a button or submitting a form), you can use getText() to ensure that the content has updated appropriately.

				
					WebElement submitButton = driver.findElement(By.id("submit"));
submitButton.click();
WebElement confirmationMessage = driver.findElement(By.id("confirmation"));
String confirmationText = confirmationMessage.getText();
System.out.println("Confirmation Text: " + confirmationText);
				
			

Example

				
					import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class GetTextExample {
    public static void main(String[] args) {
        // Set path to the ChromeDriver executable
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        // Initialize WebDriver (ChromeDriver in this case)
        WebDriver driver = new ChromeDriver();

        // Navigate to a page
        driver.get("https://www.example.com");

        // Find an element and retrieve its text
        WebElement header = driver.findElement(By.id("header"));
        String headerText = header.getText();
        System.out.println("Header text: " + headerText);

        // Find another element and verify its text
        WebElement button = driver.findElement(By.id("submit"));
        String buttonText = button.getText();
        System.out.println("Button text: " + buttonText);

        // Close the browser
        driver.quit();
    }
}
				
			

Importance

The getText() method is important for several reasons:

  • Content Verification: It helps validate that the correct text is displayed on a page, which is crucial for testing user-facing content such as buttons, links, headings, and form error messages.
  • Dynamic Content Validation: Many web applications dynamically change their content based on user interactions. getText() is useful for ensuring that the correct dynamic content is rendered after actions like form submissions, button clicks, or data updates.
  • Text-based Assertions: In automated tests, getText() allows you to assert that the expected text appears in specific parts of the page. This is often used in assertions like “assert that the error message is displayed correctly” or “verify that a confirmation message is shown after a successful action.”
  • UI Consistency: Ensures the correct display of textual content across different devices, browsers, and screen resolutions, making it a crucial tool in cross-browser testing.

Limitations

While getText() is useful, it has some limitations:

  • Non-Visible Text: getText() only returns the visible text. It does not retrieve text from hidden elements, such as elements with display: none or visibility: hidden styles.
  • Formatting Issues: getText() strips all HTML tags and formatting. This means that getText() will return only the raw text and not any HTML, styles, or other visual content.
  • Text inside Non-Textual Elements: Some elements, such as <input>, <textarea>, or elements with a readonly or disabled state, may not return the expected text using getText(). For input fields, you should use the getAttribute("value") method to retrieve the value.
  • Dynamic Changes: If text content is loaded dynamically by JavaScript (for example, in single-page applications), there might be a slight delay in retrieving the updated text. To handle this, it may be necessary to wait for the element to become visible or update its text before using getText().

Conclusion

The getText() method is an essential tool in Selenium WebDriver for extracting and validating the visible text content of web elements. It is particularly useful in verifying that dynamic content, form submissions, and UI elements are displayed correctly. By using getText(), testers can easily assert the content of elements on the page, helping to ensure that web applications function as expected.

Key Features

  • Text Extraction: Retrieves the visible text content from a web element.
  • Content Validation: Verifies that elements display the correct content for testing purposes.
  • Dynamic Content Testing: Useful for checking that text content updates after actions like form submissions, clicks, or AJAX requests.
  • Cross-Browser Testing: Ensures that the correct text appears on different browsers, devices, and screen sizes.

Leave a Comment

Share this Doc

getText()

Or copy link

CONTENTS