How to Get Text From an Element in Selenium
After reading this article, you will be fully capable of validating the text or even reading and performing actions on text using Selenium WebDriver.
Join the DZone community and get the full member experience.
Join For FreeSelenium is the most widely used automation testing tool, which reduces human effort and efficiently handles testing the scenarios we encounter every day. One such scenario is how to get the text of an element in Selenium. Selenium offers a getText() method used to get the text of an element, i.e.; it can be used to read text values of an element from a web page.
In this article, we will understand how to get the text of an element using the getText() method offered by Selenium WebDriver. We will understand how we can fetch text from a webpage that might be present in any of the web-element. We will learn various applications of the getText() method, and by the end of this article, you will be fully capable of validating the text or even reading and performing actions on text using Selenium WebDriver.
For starters, let’s define terms.
What Is the 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.
Let us learn about these terms elaborately one by one:
Inner Text
Inner Text refers to the text that appears between the opening and closing of any tag. For example, consider the below HTML code snippet:
Let us begin!
Hello World.
Saving the above code as HTML (.html file) would open a window with contents like the one below.
So, here the text "Let us begin! Hello World" and the "Click Me!" are the texts that come between the tags above. Hence, these are the inner texts.
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-
Let us begin!
This text will be hidden:
In the code above, the text inside the span tag will not be visible on the UI as it is hidden by CSS.
Now that you know what inner text and hidden by CSS means, let us iterate our definition which says, getText() method in Selenium fetches the inner text of an element, which is not hidden by CSS and returns it as a String value. In simple terms, whatever is displayed as text on the browser will be returned as-is by the getText() method. If there is no text corresponding to a web element, an empty string is returned.
Until now, we have seen how to get the text of an element from a web page. Let us now begin with the practical application of the getText() method.
Using the GetText() Method for a Heading or a 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 the 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 below.
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;
public void setUp(){
System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
driver = new ChromeDriver();
}
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);
}
public void tearDown(){
driver.quit();
}
}
On running the above code, you will see the results shown below.
In a similar way, you can write the XPath of any paragraph element and retrieve the text for the same.
Using the 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 too. 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.
xxxxxxxxxx
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;
public void setUp(){
System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
driver = new ChromeDriver();
}
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());
}
}
public void tearDown(){
driver.quit();
}
}
On executing the code, we will see the results printing the dropdown content values as shown below.
Using the GetText() Method to Get an 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 the text present on it. The below code would fetch text from an alert and print it for this demo website.
xxxxxxxxxx
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;
public void setUp(){
System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
driver = new ChromeDriver();
}
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);
}
public void tearDown(){
driver.quit();
}
}
Run the code and see that the text present in the alert is printed on the console window.
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 stated in the beginning, we would get an empty string in return. Let us see an example such as the one below.
We have picked up the header image, which has no corresponding text, and we will be using the getText() method on the element. You will see an empty string is returned on the console without any error.
The code would look like the one below.
xxxxxxxxxx
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;
public void setUp(){
System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
driver = new ChromeDriver();
}
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());
}
public void tearDown(){
driver.quit();
}
}
On running the above code, you will see results in the console with a print statement showing an empty string returned by the getText() method.
The 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 the running example below.
In the image above, we can see the multiple attributes in the input tag like id, type, a class, and placeholder. The getAttribute() method will retrieve the value corresponding to the attribute we pass as an argument. Let us see it through the code below.
xxxxxxxxxx
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;
public void setUp(){
System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
driver = new ChromeDriver();
}
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);
}
public void tearDown(){
driver.quit();
}
}
On executing the code, you can see that the value of the Placeholder attribute is printed.
The GetText() Method vs the GetAttribute() Method
Suppose we have a following HTML component:
xxxxxxxxxx
<input name="Title" type="text" value="LambdaTest" />https://www.lambdatest.com/
Now in this HTML component, if we use the getText() method, we will get the value below.
xxxxxxxxxx
“https://www.lambdatest.com/“
// Below code will give https://www.lambdatest.com/ as output
driver.findElement(By.name("Title")).getText();
And if we use the getAttribute() method to get the value of attribute “value”
, we will get “LambdaTest”
.
xxxxxxxxxx
// Below code will give LambdaTest as output
driver.findElement(By.name("Title")).getAttribute("value");
Though both of these values are a String value, both of these are entirely different.
Therefore, we mainly use the getText() method to get the inner text of an HTML tag and getAttribute() method to get the attribute value of a Placeholder attribute.
We hope you are now clear with how to get text of an element in Selenium and the difference between the getText() and the getAttribute() methods and understand which method to use when.
Wrapping It Up
We hope you are now clear with the getText() method and can use it easily in automation testing.
If you have any issues or questions, don’t hesitate to reach out via the comment section below. Happy testing!
Published at DZone with permission of Harshit Paul, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments