0
0
Selenium-pythonHow-ToBeginner ยท 3 min read

How to Get Text of Element in Selenium: Simple Guide

To get the text of an element in Selenium, use the getText() method on the WebElement object. This method returns the visible text inside the element as a string.
๐Ÿ“

Syntax

The basic syntax to get text from a web element in Selenium is:

  • WebElement element = driver.findElement(By.locator("value")); - Finds the element on the page.
  • String text = element.getText(); - Retrieves the visible text inside the element.
java
WebElement element = driver.findElement(By.id("exampleId"));
String text = element.getText();
๐Ÿ’ป

Example

This example shows how to open a webpage, find a heading element by its ID, and print its text content.

java
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) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com");
            WebElement heading = driver.findElement(By.id("main-heading"));
            String text = heading.getText();
            System.out.println("Text of element: " + text);
        } finally {
            driver.quit();
        }
    }
}
Output
Text of element: Example Domain
โš ๏ธ

Common Pitfalls

  • Using getText() on elements without visible text: It returns an empty string if the element has no visible text.
  • Trying to get text from input fields: Use getAttribute("value") instead because getText() returns empty for inputs.
  • Incorrect locator: If the element is not found, findElement throws an exception.
java
/* Wrong: Trying to get text from input field */
WebElement input = driver.findElement(By.id("username"));
String text = input.getText(); // Returns empty string

/* Right: Use getAttribute for input value */
String value = input.getAttribute("value");
๐Ÿ“Š

Quick Reference

Remember these key points when getting text in Selenium:

  • getText() returns visible text inside elements like <div>, <span>, <p>.
  • For input or textarea elements, use getAttribute("value").
  • Always ensure your locator finds the correct element.
  • Handle exceptions when elements are not found.
โœ…

Key Takeaways

Use getText() method on WebElement to get visible text content.
For input fields, use getAttribute("value") instead of getText().
Ensure your element locator is correct to avoid exceptions.
getText() returns empty string if element has no visible text.
Always close the browser session after test execution.