How To Get Text Of An Element In Selenium?

What Is getText() Method?

The Selenium WebDriver interface has predefined the getText() method, which helps retrieve the text for a specific web element. This method gets the visible, inner text (which is not hidden by CSS) of the web-element.

Inner Text

Inner Text refers to the text that appears between opening and closing of any tag. For example, consider the below HTML code snippet:

Not Hidden By CSS

There is one more thing mentioned in the definition above, i.e., not hidden by CSS. Let us understand that too. Consider the following HTML snippet-

Using getText() Method To Get Heading Or Paragraph

We all know that no website is complete without headings or paragraph content. At times it becomes necessary to verify the text on the web page we are landing on. The getText() method in Selenium helps us retrieve a text and do necessary action on it. In the code below, we are reading the heading text from the web page, comparing it with the expected value, and then printing the results. We will be using this demo website to practice this automation example here.

package getText;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;


public class TextThruHeading {

WebDriver driver;

@BeforeTest
public void setUp(){
System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
driver = new ChromeDriver();
}

@Test
public void headingText(){
driver.get("https://phptravels.com/demo/");
driver.manage().window().maximize();
String expectedHeading = "APPLICATION TEST DRIVE";

//Storing the text of the heading in a string
String heading = driver.findElement(By.xpath("//div[@class='text']//h2")).getText();
if(expectedHeading.equalsIgnoreCase(heading))
System.out.println("The expected heading is same as actual heading --- "+heading);
else
System.out.println("The expected heading doesn't match the actual heading --- "+heading);
}
@AfterTest
public void tearDown(){
driver.quit();
}
}

Using getText() Method To Get A Dropdown Text

There are multiple cases when we need to select a specific dropdown value, or maybe get the text values in a dropdown. We can use the getText() method to handle such scenarios as well. We will now see how we can get the values in a dropdown and print the same in the console. To run the script for dropdown, we have used this demo website.

package getText;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TextThruDropdown {

WebDriver driver;

@BeforeTest
public void setUp(){
System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
driver = new ChromeDriver();
}

@Test
public void headingText(){
driver.get("https://demoqa.com/select-menu");
driver.manage().window().maximize();
// Working on the third dropdown, viz, Old Style Select menu
WebElement drpdn = driver.findElement(By.id("oldSelectMenu"));
System.out.println("Clicking on the drop down");
Select se = new Select(drpdn);
List<WebElement> opt = se.getOptions();
System.out.println("The total number of options in the dropdown is : " +opt.size());

//Iterate through the list of options
System.out.println("The dropdown values are--- ");
for(WebElement options : opt){
System.out.println(options.getText());
}

}
@AfterTest
public void tearDown(){
driver.quit();
}
}

Using getText() Method To Get Alert Text

Just like the paragraph and dropdown, one can retrieve the text of an alert as well. Alerts are common with many applications, and hence there can be a need to check text present on it. The below code would fetch text from an alert and print it for this demo website.

package getText;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class AlertText {
WebDriver driver;

@BeforeTest
public void setUp(){
System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
driver = new ChromeDriver();
}

@Test
public void alertText(){
driver.get("https://demoqa.com/alerts");
driver.manage().window().maximize();
driver.findElement(By.id("confirmButton")).click();
String txt = driver.switchTo().alert().getText();
System.out.println("The text is - " +txt);
}
@AfterTest
public void tearDown(){
driver.quit();
}
}

How To Get Null Or Blank Text Values Using The getText() Method?

There might be cases when your web element doesn’t contain a text value at all. What do you think would happen if we apply the getText() method to such an element? As already told in the beginning, we would get an empty string in return. Let us see an example:

package getText;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class NullText {

WebDriver driver;

@BeforeTest
public void setUp(){
System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
driver = new ChromeDriver();
}

@Test
public void headingText(){
driver.get("https://demoqa.com");
driver.manage().window().maximize();
WebElement ele = driver.findElement(By.xpath("//header//img"));
System.out.println("The header text is - " +ele.getText());

}
@AfterTest
public void tearDown(){
driver.quit();
}
}

Difference Between getText() And getAttribute() In Selenium WebDriver

People generally get confused between getText and getAttribute methods a lot. Note that both these methods are entirely different and return different values.

getText() Method

The getText() method returns the visible inner text of a web element. You can refer to any of the above-stated examples to get the idea of getText() method.

getAttribute() Method

On the other hand, getAttribute() method fetches the value of the attribute we wish to retrieve. Let us see the getAttribute() method through a running example:

package getText;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class GetAttribute {
WebDriver driver;

@BeforeTest
public void setUp(){
System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
driver = new ChromeDriver();
}

@Test
public void attributeText(){
driver.get("https://www.lambdatest.com/");
driver.manage().window().maximize();
// This line would store the attribute value as String variable
String attributeValue = driver.findElement(By.id("useremail")).getAttribute("placeholder");
System.out.println("The value is - " + attributeValue);
}
@AfterTest
public void tearDown(){
driver.quit();
}
}

getText() Method Vs. getAttribute() Method

Suppose we have a following HTML component:

<input name="Title" type="text" value="LambdaTest" />https://www.lambdatest.com
https://www.lambdatest.com// Below code will give https://www.lambdatest.com/ as output
driver.findElement(By.name("Title")).getText();
// Below code will give LambdaTest as output
driver.findElement(By.name("Title")).getAttribute("value");

Execute Your Tests In Parallel Using LambdaTest Selenium Grid

When you are working on automation, you have to execute your tests across multiple browsers at the same time. LambdaTest offers you the platform to execute cross browser testing with the same code on their Selenium grid. All you need to do is set up some properties in your code, connect to the lambda grid host using your user name, and access key as variables.

package getText;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TestClass {

public String username = "YOUR_USERNAME";
public String accesskey = "YOUR_ACCESS_KEY";
public static RemoteWebDriver driver = null;
public String gridURL = "@hub.lambdatest.com/wd/hub";
boolean status = false;

@BeforeTest
public void setUp(){
//You need to set desired capabilities which you can generate from Capability Generator from Lambda Test as per your requirements
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("version", "81.0");
capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will get any available one
capabilities.setCapability("build", "LambdaTestProject");
capabilities.setCapability("name", "LambdaTestGetTextProject");
capabilities.setCapability("network", true); // Enables network logs
capabilities.setCapability("visual", true); // Enables step by step screenshot
capabilities.setCapability("video", true); // Enables video recording
capabilities.setCapability("console", true); // Captures console logs
try {
driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
} catch (MalformedURLException e) {
System.out.println("Invalid grid URL");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

@Test
public void testMethod(){
driver.get("https://www.lambdatest.com/");
driver.manage().window().maximize();
System.out.println("The title of the page is - "+driver.getTitle());
}
@AfterTest
public void tearDown(){
driver.quit();
}

}

Wrapping It Up!

We hope you are now clear with the getText() method and can use it easily in the automation testing. You can also use the LambdaTest platform to perform live interactive and automated Cross Browser Testing on 2000+ real browsers and operating systems online.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store