How to Get Text of an Element in Selenium: Tutorial

This guide explores how to get text of an element in Selenium using Java and Python to find web elements and how to test its cross browser compatibility

Get Started free
Guide Banner Image
Home Guide How to Get Text of an Element in Selenium: Tutorial

How to Get Text of an Element in Selenium: Tutorial

A WebElement is a part of DOM (Document Object Model) that helps users interact with a webpage or website. These are basically HTML elements and handling such WebElements is the key in Selenium automation. Selenium WebDriver provides several methods to deal with these WebElements effectively.

There are times when QAs may need to retrieve the text of an element for various purposes like locating an element by its text, verifying error messages, asserting the presence of an element by its visible text, and so on. Selenium getText() is one such method that serves the purpose.

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

getText() Method Example: Verify the “Get started free” button

Let us understand 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:

Get Text of an Element in Selenium Example

Code Snippet to verify the “Get started free” button with Java

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

 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 3000+ 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.

Run Selenium Tests for Free

Let’s see the below 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.

Executing Selenium Get Text of an Element Test on BrowserStack

Text Logs of how our execution progressed

Text logs how execution progressed

Desired capabilities set by the user

Setting Desired Capabilities for Get Text of an Element in Selenium example

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 3000+ 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.

Run Selenium Tests on BrowserStack

Tags
Automated UI Testing Selenium Selenium Webdriver