Codementor Events

How To Find Element By Text In Selenium WebDriver

Published Apr 06, 2022
How To Find Element By Text In Selenium WebDriver

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.

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

WebElement elementName= driver.findElement(By.<LocatorStrategy>("LocatorValue"));

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

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.

XPath = //tagname[[@Attribute](http://twitter.com/Attribute)=’Value’]

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:

    WebElement ele = driver.findElement(By.xpath(“//<tagName>[text()=’text value’]”))

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:

WebElement ele=driver.findElement(By.xpath(“//<tagName>[contains(text(),’textvalue’)]”))

Let us now read about these in detail.

Note: The ConnectionClosedException occured whenever connection between driver and client has been lost and client is sending the request to the driver after disconnecting the driver.

Generally, This exception is more related to UnreachableBrowserException for chomre webdriver and firefox browser except Safari.

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.

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.

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:

WebElement checkbox= driver.findElement(By.xpath(“//a[text()=’Checkbox Demo’]”))

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

You can refer to the below testcase.

package LambdaTest;
 
    import org.openqa.Selenium.By;
    import org.openqa.Selenium.WebElement;
    import org.openqa.Selenium.remote.DesiredCapabilities;
    import org.openqa.Selenium.remote.RemoteWebDriver;
    import org.testng.Assert;
    import org.testng.annotations.AfterTest;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.Listeners;
    import org.testng.annotations.Test;
 
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.List;
 
    [@Listeners](http://twitter.com/Listeners)({util.Listener.class})
    class AutomationUsingFindElementByText {
 
        public String username = "YOUR USERNAME";
        public String accesskey = "YOUR ACCESSKEY";
        public static RemoteWebDriver driver = null;
        public String gridURL = "[@hub](http://twitter.com/hub).lambdatest.com/wd/hub";
 
        [@BeforeTest](http://twitter.com/BeforeTest)
        public void setUp() throws Exception {
           DesiredCapabilities capabilities = new DesiredCapabilities();
            capabilities.setCapability("browserName", "chrome");
            capabilities.setCapability("version", "96.0");
            capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get the any available one
            capabilities.setCapability("build", "AutomationUsingFindElement");
            capabilities.setCapability("name", "AutomationUsingFindElementSuite");
            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](http://twitter.com/Test)
        public void findElementByCompleteTextMatch() {
            try {
                System.out.println("Logging into Lambda Test Selenium Playground");
                driver.get("[http://labs.lambdatest.com/Selenium-playground/](http://labs.lambdatest.com/Selenium-playground/)");
 
                WebElement checkBoxDemoPage= driver.findElement(By.xpath("//a[text()='Checkbox Demo']"));
                checkBoxDemoPage.click();
                System.out.println("Clicked on the Checkbox Demo Page");
 
                WebElement header=driver.findElement(By.xpath("//h1"));
                System.out.println("The header of the page is:"+header.getText());
            } catch (Exception e) {
 
            }
 
        }
 
 
        [@AfterTest](http://twitter.com/AfterTest)
        public void closeBrowser() {
            driver.close();
            System.out.println("The driver has been closed.");
 
        }
 
    }

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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "[http://testng.org/testng-1.0.dtd](http://testng.org/testng-1.0.dtd)">
<suite  name="AutomationUsingFindElementSuite">
 
    <test name="AutomationUsingFindElementTest" >
        <classes>
            <class name="LambdaTest.AutomationUsingFindElementByText" >
            </class>
        </classes>
    </test>
</suite>

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

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="[http://maven.apache.org/POM/4.0.0](http://maven.apache.org/POM/4.0.0)"
         xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance](http://www.w3.org/2001/XMLSchema-instance)"
         xsi:schemaLocation="[http://maven.apache.org/POM/4.0.0](http://maven.apache.org/POM/4.0.0) [http://maven.apache.org/xsd/maven-4.0.0.xsd](http://maven.apache.org/xsd/maven-4.0.0.xsd)">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>org.example</groupId>
    <artifactId>LambdaTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.Seleniumhq.Selenium</groupId>
            <artifactId>Selenium-api</artifactId>
            <version>4.0.0-alpha-7</version>
        </dependency>
        <dependency>
            <groupId>org.Seleniumhq.Selenium</groupId>
            <artifactId>Selenium-remote-driver</artifactId>
            <version>4.0.0-alpha-7</version>
        </dependency>
        <dependency>
            <groupId>org.Seleniumhq.Selenium</groupId>
            <artifactId>Selenium-chrome-driver</artifactId>
            <version>4.0.0-alpha-7</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
        </dependency>
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>4.4.3</version>
        </dependency>
    </dependencies>
 
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
 
</project>

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

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.

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

[@Listeners](http://twitter.com/Listeners)(PackageName.ClassName.class)

3. @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.

4. @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.

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

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

Console Output

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

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.

Note: The ConnectionFailedException occured when client is not able to establish connection with selenium hub or webdriver endpoints.

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.

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

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:

List<WebElement> listName= driver.findElements(By.<LocatorStrategy>(“LocatorValue”))

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

List<WebElement> tableOptions=driver.findElements(By.xpath(“//a[contains(text(),’Table’)”)

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

You can refer to the below testcase.

package LambdaTest;
 
    import org.openqa.Selenium.By;
    import org.openqa.Selenium.WebElement;
    import org.openqa.Selenium.remote.DesiredCapabilities;
    import org.openqa.Selenium.remote.RemoteWebDriver;
    import org.testng.Assert;
    import org.testng.annotations.AfterTest;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.Listeners;
    import org.testng.annotations.Test;
 
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.List;
 
    [@Listeners](http://twitter.com/Listeners)({util.Listener.class})
    class AutomationUsingFindElementByText {
 
        public String username = "YOUR USERNAME";
        public String accesskey = "YOUR ACCESSKEY";
        public static RemoteWebDriver driver = null;
        public String gridURL = "[@hub](http://twitter.com/hub).lambdatest.com/wd/hub";
 
        [@BeforeTest](http://twitter.com/BeforeTest)
        public void setUp() throws Exception {
           DesiredCapabilities capabilities = new DesiredCapabilities();
            capabilities.setCapability("browserName", "chrome");
            capabilities.setCapability("version", "96.0");
            capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get the any available one
            capabilities.setCapability("build", "AutomationUsingFindElement");
            capabilities.setCapability("name", "AutomationUsingFindElementSuite");
            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](http://twitter.com/Test)
        public void findElementByPartialTextMatch() {
            try {
                System.out.println("Logging into Lambda Test Selenium Playground");
                driver.get("[http://labs.lambdatest.com/Selenium-playground/](http://labs.lambdatest.com/Selenium-playground/)");
                List<WebElement> tableOptions= driver.findElements(By.xpath("//a[contains(text(),'Table')]"));
                for(WebElement e: tableOptions){
                    System.out.println("The different options with table in name are:"+e.getText());
                }
 
            } catch (Exception e) {
 
            }
 
        }
 
        [@AfterTest](http://twitter.com/AfterTest)
        public void closeBrowser() {
            driver.close();
            System.out.println("The driver has been closed.");
 
        }
 
    }

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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "[http://testng.org/testng-1.0.dtd](http://testng.org/testng-1.0.dtd)">
<suite  name="AutomationUsingFindElementSuite">
 
    <test name="AutomationUsingFindElementTest" >
        <classes>
            <class name="LambdaTest.AutomationUsingFindElementByText" >
            </class>
        </classes>
    </test>
</suite>

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

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="[http://maven.apache.org/POM/4.0.0](http://maven.apache.org/POM/4.0.0)"
         xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance](http://www.w3.org/2001/XMLSchema-instance)"
         xsi:schemaLocation="[http://maven.apache.org/POM/4.0.0](http://maven.apache.org/POM/4.0.0) [http://maven.apache.org/xsd/maven-4.0.0.xsd](http://maven.apache.org/xsd/maven-4.0.0.xsd)">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>org.example</groupId>
    <artifactId>LambdaTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.Seleniumhq.Selenium</groupId>
            <artifactId>Selenium-api</artifactId>
            <version>4.0.0-alpha-7</version>
        </dependency>
        <dependency>
            <groupId>org.Seleniumhq.Selenium</groupId>
            <artifactId>Selenium-remote-driver</artifactId>
            <version>4.0.0-alpha-7</version>
        </dependency>
        <dependency>
            <groupId>org.Seleniumhq.Selenium</groupId>
            <artifactId>Selenium-chrome-driver</artifactId>
            <version>4.0.0-alpha-7</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
        </dependency>
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>4.4.3</version>
        </dependency>
    </dependencies>
 
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
 
</project>

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.

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

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.

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!!

Discover and read more posts from Riadayal
get started