Continuous Test Orchestration And Execution Platform Online

Perform automated and live-interactive testing on 3000+ real desktop and mobile devices online.

How To Find Element By Text In Selenium WebDriver

Ria Dayal

Posted On: April 1, 2022

view count66563 Views

Read time11 Min Read

Find element by Text in Selenium is used to locate a web element using its text attribute. The text value is used mostly when the basic element identification properties such as ID or Class are dynamic in nature, making it hard to locate the web element.

Sometimes, developers tend to group similar web elements with the same ID or the same Class together. For example, if you have an element with the tag as Button which has a dynamic ID and Class name, where ID is getting changed from ‘ID-3465-text1’ to ‘ID-4434-textE2,’ and the Class name gets changed from “ID-Class-text45” to “ID-Class-text73” on every new session.

Element Find Selenium

Source

In such cases, it becomes very difficult to locate the web elements using ID or Class attribute, and this is when the Text attribute comes to the rescue while performing Selenium automation testing.

The text value can be fully matched or partially matched to locate the element. In this article on how to find element by text in Selenium WebDriver, you will read about how to use the Text attribute in order to find any element.

Let’s get started!

What is Find Element In Selenium?

When you start writing your Selenium automation script, interaction with web elements becomes your first and a very vital step because it’s the WebElements that you play around with within your test script. Now, interaction with these web elements can only happen if you identify them using the right approach.

Find Element method in Selenium is a command which helps you identify a web element. There are multiple ways that Find Element provides to uniquely identify a web element within the web page using Web locators in Selenium like ID, Name, Class Name, etc. Here is the syntax of Find Element In Selenium.

The syntax of Find Element is

As shown in the above syntax, this command accepts the “By” object as the argument and returns a WebElement object. The “By” is a locator or query object and accepts the locator strategy. The Locator Strategy can assume the below values:

  • ID
  • Name
  • Class Name
  • Tag Name
  • Link Text
  • Partial Link Text
  • XPath
  • CSS Selector

Also readFindElement And FindElements In Selenium [Differences]

What is Find Element By Text in Selenium?

We saw in the previous section about find element in Selenium and its syntax. Now, you must be wondering how to find element by text in Selenium WebDriver.

The answer is by making use of XPath in Selenium!!

Wondering how? Let’s look at the sections below.

In order to use Text, you will need to make use of XPath as your Locator Strategy and the text attribute of the element in the Locator Value.

The basic format of XPath in Selenium is as below.

However, before we get started, it’s important to understand two built-in methods of Selenium, which will ultimately be used in findElement.

  1. text() – This is a built-in method in Selenium that is used with XPath in order to locate an element based on its exact text value. The syntax of using text() with findElement is:
  2. contains() – Similar to the text() method, contains() is another built-in method which is used with XPath. However, this is used when we want to write the locator based on a partial text match. The syntax of using text() & contains() with findElement is:

Let us now read about these in detail.

Find Element by Text in Selenium for Complete Text match

Now that you saw the syntax for using text() in case of complete text match. In this section on how to find element by text in Selenium, let us see it using an example.

We will use Selenium Playground offered by LambdaTest for understanding the same. LambdaTest is a cloud-based cross browser testing platform that supports Selenium Grid, providing a solution to every obstacle you face while performing automation testing using your local machine. Test Automation Platforms like LambdaTest offer a Selenium Grid consisting of 3000+ online browsers for you to perform Selenium automation testing effortlessly.

Selenium Playground

Use Case

  1. Log in to Selenium Playground.
  2. Identify the Web Element for the Checkbox Demo link on the above web page using the text() method.
  3. Click on it and print the page header.

Implementation

We will implement the case using Selenium with Java and use the cloud Selenium Grid offered by LambdaTest for executing our test case.
Selenium Grid refers to a software testing setup that enables QAs to perform parallel testing across multiple browsers and devices with unique operating systems. When the entire setup of Selenium Grid is accessible using cloud-based servers, it is called Selenium Grid Cloud. An online Selenium Grid helps you focus on writing better Selenium test scripts rather than worrying about infrastructure maintenance.

Let us now inspect the locator for the Checkbox Demo page. In order to inspect, you can simply right-click on the Web Element and click on Inspect. On the Elements tab, you can start writing your locator.

Selenium - Find Element with Text
As shown in the above picture, we use the Checkbox Demo text with its tag a for a complete match, and hence, the correct implementation here would be:

Let us now use the same and write our test case.

You can refer to the below testcase.

You can use the below testng.xml file for running the above testcase.

And the below pom.xml file for installing all the necessary dependencies.

Github

Code Walkthrough

In this section on how to find element by text in Selenium, let’s look at the different areas of code in detail.

  1. Imported Dependencies: Here, we have imported all the necessary classes of Selenium WebDriver, WebDriverWait, Desired Capabilities, and RemoteWebDriver to set the respective browser capabilities and run the test cases on the grid.
  2. Selenium Element Finding with Text

  3. Global Variables: As we have used a Selenium Grid Cloud like LambdaTest to perform our test execution, we are using the below-shown variables.

    Here, you can populate the values for your corresponding username and access key, which can be collected by logging into your LambdaTest Profile Section. You can copy the Username and the Access Token to be used in the code. However, the grid URL will remain the same, as shown below.

  4. Selenium Element Find with Text

    We have also used the Listener class here in order to customize the TestNG Report. TestNG provides us with a lot of Listeners (e.g., IAnnotationTransformer, IReporter, etc.). These interfaces are used while performing Selenium automation testing mainly to generate logs and customize the TestNG reports.

    Also read: How To Use TestNG Reporter Log In Selenium

    To implement the Listener class, you can simply add an annotation in your test class just above your class name.
    Syntax:

    Element Find of Selenium by Text

  5. @BeforeTest(Setup Method): Here, we have used the LambdaTest Desired Capabilities Generator and have set the necessary capabilities of browser name, version, platform, etc., for our Selenium Remote WebDriver. After that, we are opening the website in the launched browser.
  6. Finding Element by Text in Selenium

  7. @Test(findElementByCompleteTextMatch): In this case, we are first logging into the Selenium Playground web page. After that, we locate the Checkbox Demo button using a complete text match and click on the same. In the end, we are printing the header of the web page.
  8. Finding Element by Text

  9. @AfterTest(closeBrowser): Here, we are just closing the launched browser.

Element Finding in Selenium

Once the tests are completed, you can also view your test results, logs, and the test recording as well in your LambdaTest Automation Dashboard.

Element Finding in Selenium

Console Output

Once you run the test case, the console output will look something like the below:

Element Finding with Text

The below video will help you write your first test script in Selenium using Java by interacting with different web elements.

You can also Subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorials around Selenium testing, Cypress E2E testing, CI/CD, and more.

Find Element by Text in Selenium for Partial Text match

In the previous example of this article on how to find element by text in Selenium WebDriver, you saw how you could use findElement by Text for a complete text match. In this section, we will understand how we can use partial Text match in order to locate web elements.

Also readFind Elements With Link Text & Partial Link Text In Selenium

Use Case

  1. Log in to Selenium Playground.
  2. Identify all the Web Elements which have a table in their names.
  3. Print the text of all such Web Elements.

Let us see the locator for the above test case.

Implementation

Text Method for Element Finding in Selenium

As shown in the above picture, we use the Table text with its tag a for a partial match, and as a result, we get a total of 5 Web Elements using the above locator. Since there are more than 1 Web Element, in this case, we will use FindElements.

FindElements in Selenium returns you the list of web elements that match the locator value, unlike FindElement which returns only a single web element. In case, there are no matching elements within the web page, FindElements returns an empty list.

The syntax of FindElements in Selenium is:

Hence, the correct implementation using FindElements with partial text match here would be:

Let us now use the same and write our test case.

You can refer to the below testcase.

You can use the below testng.xml file for running the above testcase.

And the below pom.xml file for installing all the necessary dependencies.

GitHub

Also, readHow To Get Text Of An Element In Selenium?

Code Walkthrough

In this section on how to find element by text in Selenium, let us now check the test case walkthrough in detail. The BeforeTest and import statements remain the same as we saw in our previous example.

@Test(findElementByPartialTextMatch): In this case, we are first logging into the Selenium Playground web page. After that, we locate all the Web Elements which have Table in their text and store them in a list. Later, we iterate over the list and print their text.

Element Finding from Text in Selenium

Once the tests are completed, you can also view your test results, logs, and the test recording as well in your LambdaTest Automation Dashboard.

Text Method in Selenium for Element

You can also see the test results on the LambdaTest Analytics Dashboard. The dashboard shows all the details and metrics related to your tests.

Navigate to the LambdaTest Analytics Dashboard to view the metrics of your tests. You can quickly assess test performance and overall health from Test Overview. The Test Summary will show how many passed and failed tests your team has run and the overall efficiency of these tests.

Element Finding through Text in Selenium

Console Output

Once you run the test case, the console output will look something like the below:

If you’re a developer or a tester and want to take your skills to the next level, this Selenium 101 certification from LambdaTest can help you reach that goal.

Here’s a short glimpse of the Selenium 101 certification from LambdaTest:

Conclusion

In this Selenium Java tutorial on how to find element by text in Selenium WebDriver, we explored finding an element using text in Selenium. We saw how we could use the text() method in case of both complete and partial text matches. We also saw how we could use it in the case of FindElements and get a list of Web Elements through text match. In the end, we also implemented the cases using Selenium with Java on a cloud Selenium Grid.

Honestly, using text() is one of my personal favorite methods in Selenium when it comes to locating Web Elements, as it’s very easy to implement and can be tweaked in any way to match our use case.

I hope you enjoyed reading this article on how to find element by text in Selenium, learned some more about FindElement By Text, and I believe this method will become your personal favorite too. 🙂

Happy Testing!!

Frequently Asked Questions (FAQs)

How do you search text in Selenium?

The ‘findElement’ method returns a WebElement object. This object has a ‘getText’ method, which returns the visible text on that element. To find a particular element, use the ‘findElement’ method with appropriate locators.

What is text () in XPath?

In XPath, text() is a node test that matches a text node. A text node is the kind of node that contains the text between the start and end tags when elements are written in HTML source code or in XML source code.

How do I find an element in Selenium?

You can use the following methods:

  1. ID.
  2. Name.
  3. ClassName.
  4. TagName.
  5. Link Text/Partial Link Text.
  6. CSS Selector.
  7. XPATH Selector.

Author’s Profile

Ria Dayal

A Senior Quality Engineer By Profession, an automation enthusiast and loves to anchor. Her expertise revolves around Selenium, Java, Rest Assured, and Jenkins. Shell scripting too interests her a lot. Ria enjoys reading novels and writing is her comfort zone.

Blogs: 11



linkedintwitter

Test your websites, web-apps or mobile apps seamlessly with LambdaTest.

  • Selenium, Cypress, Playwright & Puppeteer Testing
  • Real Devices Cloud
  • Native App Testing
  • Appium Testing
  • Live Interactive Testing
  • Smart Visual UI Testing
Book a Demo