How to Find Element by Text in Selenium
Vipul Gupta
Posted On: June 2, 2025
187966 Views
11 Min Read
Locating WebElements precisely is essential for reliable Selenium testing. One commonly used technique is to find elements by text in Selenium, which helps identify elements based on their visible text, especially when other attributes aren’t unique or consistent.
TABLE OF CONTENTS
What Is Find Element by Text in Selenium?
Find element by text in Selenium is a way to locate a WebElement based on its visible text content using the findElement() method. It is useful when attributes like ID or ClassName are dynamic or unreliable for identification.
XPath is typically used as the locator strategy, leveraging the text() method to find element by text in Selenium.
1 |
driver.findElement(By.xpath("//*[text()='Submit']")); |
Methods to Find Element by Text in Selenium
To find element by text in Selenium, you can use the text() and contains() methods in your XPath with the findElement() method.
- text(): This built-in method in Selenium is used with XPath to locate an element based on its exact text value:
1WebElement ele = driver.findElement(By.xpath(“//[text()=’textvalue’]”))
You can also extract text from a web page and print it in the console using the getText() method.
- contains(): It is another built-in method which is used with XPath. However, this is used when writing the locator based on a partial text match.
1WebElement ele =driver.findElement(By.xpath(“//[contains(text(),’textvalue’)]”))
Using findElement() Method for Complete Text Match
To find element by text in Selenium for complete text match, you can use the findElement() method. Here’s an example:
Test Scenario:
|
Typically, you might run Selenium scripts on a local grid setup. However, here we’ll execute the test script on an online Selenium Grid using LambdaTest. This allows us to run tests in parallel across various browser and OS combinations without managing any infrastructure.
To get started, check out this documentation on Selenium testing with LambdaTest.
Run Selenium tests across 3000+ real environments. Try LambdaTest Now!
Step 1: Inspect the Element
-
- Open the web page and right-click on the Checkbox Demo link.
- Click Inspect to open the browser developer tools. In the Elements tab, you’ll see the HTML structure of the web page.
- Use the anchor tag (a) and the text “Checkbox Demo” to find this element using XPath.
1WebElement checkbox = driver.findElement(By.xpath("//a[text()='Checkbox Demo']"));
Step 2: Setup Project
- Open Eclipse IDE and create a Maven project named FindElementByText.
- Inside the src folder, add a new package named test to hold all test files.
- Create a BaseTest.java file to handle WebDriver setup, teardown, and LambdaTest cloud grid connection.
Step 3: Implementation
- Update your pom.xml file with Selenium and TestNG dependencies.
123456789101112131415161718192021222324252627282930313233<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>FindElementByText</groupId><artifactId>FindElementByText</artifactId><version>0.0.1-SNAPSHOT</version><build><sourceDirectory>src</sourceDirectory><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><release>17</release></configuration></plugin></plugins></build><dependencies><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-java</artifactId><version>4.16.1</version></dependency><dependency><groupId>org.testng</groupId><artifactId>testng</artifactId><version>7.8.0</version><scope>test</scope></dependency></dependencies></project> - Create BaseTest.java file to set up and tear down the WebDriver, with connectivity to LambdaTest Selenium Grid.
12345678910111213141516171819202122232425262728293031323334353637383940public class BaseTest {public RemoteWebDriver driver = null;String username = System.getenv("LT_USERNAME") == null ? "<lambdatest_username>" : System.getenv("LT_USERNAME");String accessKey = System.getenv("LT_ACCESS_KEY") == null ? "<lambdatest_accesskey>" : System.getenv("LT_ACCESS");@BeforeTestpublic void setup(){try{ChromeOptions chromeOptions = new ChromeOptions();chromeOptions.setPlatformName("Windows 10");chromeOptions.setBrowserVersion("121.0");HashMap<String, Object> ltOptions = new HashMap<String, Object>();ltOptions.put("build", "Find Element by Text");ltOptions.put("project", "Find Element by Text in Selenium");chromeOptions.setCapability("LT:Options", ltOptions);driver = new RemoteWebDriver(new URL("https://" + username + ":" + accessKey + "@hub.lambdatest.com/wd/hub"), chromeOptions);}catch (MalformedURLException e){e.printStackTrace();}}@AfterTestpublic void tearDown(){driver.quit();}}
You can get your LambdaTest Username and Access Key from your Account Settings > Password & Security to connect to the cloud grid for test execution. Alternatively, you can configure these as environment variables and directly fetch them in the test script.
After that, create a HashMap type variable to pass the additional browser capabilities required by the LambdaTest platform to support test execution on their cloud grid.
You can fetch the required browser capabilities for the LambdaTest platform by navigating to the Automation Capabilities Generator.
- Create TestFindByTextForCompleteMatch.java file to perform the actual text match operation.
123456789101112131415public class TestFindByTextForCompleteMatch extends BaseTest{@Testpublic void testFindElementByCompleteTextMatch(){System.out.println("Logging into Lambda Test Selenium Playground");driver.get("https://www.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());}}
Once the tests are executed, you can view your test results on the LambdaTest Web Automation dashboard.
Using findElement() Method for Partial Text Match
To find element by text in Selenium for a partial text match, you can use XPath with the contains() method.
Test Scenario:
- Log in to the LambdaTest Selenium Playground.
- Identify all the WebElements that have “Table” in their names.
- Print the text of all such WebElements.
Step 1: Inspect the Element
-
- Right-click on any WebElement with “Table” in its name and select Inspect to open the browser developer tools.
- In the Elements tab, use the anchor tag and partial text “Table” with XPath contains() method to locate these elements.
If there are more than one WebElement, you can use the findElements() method.
The findElements() method returns the list of WebElements that match the locator value, unlike the findElement() method, which returns only a single WebElement.
If there are no matching elements within the web page, the findElements() method returns an empty list.
1List tableOptions=driver.findElements(By.xpath(“//a[contains(text(),’Table’)”)Step 2: Implementation
Create a new test class file named TestFindByTextForPartialMatch.java and add the following code.
123456789101112131415public class TestFindByTextForPartialMatch extends BaseTest {@Testpublic void testFindElementByPartialTextMatch() {System.out.println("Logging into Lambda Test Selenium Playground");driver.get("https://www.lambdatest.com/selenium-playground/");List 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());}}}Once the test executes, you can verify the results in the LambdaTest Web Automation dashboard.
Using findElement() Method With text() and contains() Methods
Let’s look at how to find element by text in Selenium for finding a WebElement that contains a specific text using the text() and contains() methods.
Test Scenario:
- Log in to the LambdaTest Selenium Playground.
- Identify WebElements that have “Dynamic” in its name and click on it.
- Print the header of the loaded page after the action.
Step 1: Inspect the Element
Right-click on the Dynamic Data Loading link and select Inspect to open developer tools and identify the element’s locator.
Step 2: Implementation
We target the element containing the specific text “Dynamic” to perform the click action. To achieve this, we use the findElement() method with an XPath expression that combines the text() and contains() methods.
1WebElement element= driver.findElement(By.xpath(“//a[contains(text(),’Dynamic’)”)Create a new test class file called TestFindByTextForSpecificContainingText.java and add the below code to perform a set of actions.
1234567891011121314public class TestFindByTextForSpecificContainingText extends BaseTest {@Testpublic void testFindElementBySpecificTextMatch() {System.out.println("Logging into Lambda Test Selenium Playground");driver.get("https://www.lambdatest.com/selenium-playground/");WebElement element = driver.findElement(By.xpath("//a[contains(text(),'Dynamic')]"));element.click();System.out.println("Clicked on the Dynamic Data Loading link");WebElement header = driver.findElement(By.xpath("//h1"));System.out.println("The header of the page is:" + header.getText());}}Once the tests are executed, you can view your test results on the LambdaTest Web Automation dashboard.
Conclusion
In this blog on how to find element by text in Selenium, we explored finding an element using text in Selenium. We saw how to use the text() method in complete and partial text matches. We also saw how we can use it in the case of the findElements() method and get a list of WebElements through text match.
You can also check this blog on findElement() and findElements() in Selenium to know their key differences.
Frequently Asked Questions (FAQs)
How do you search for text in Selenium?
The findElement() method returns a WebElement object. This object has a getText() method, which returns the visible text on that element. Use the findElement() method with appropriate locators to find a particular element.
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 XML source code.
How to find an element by text in XPath?
You can use the text content of an element in your XPath expression to locate it. This is helpful when the element doesn’t have unique attributes, and you want to match it based on the exact words it shows on the web page.
What is the purpose of getText() and getAttribute() in Selenium?
The getText() method is used to read the visible text of a web element on the page, while the getAttribute() method lets you access the value of a specific attribute of that element, such as its link, placeholder, or any custom property.
How do you find elements in Selenium?
In Selenium, you can find elements using different types of locators such as ID, Name, TagName, ClassName, XPath, CSS Selector, etc. The best method to use depends on how the element is defined in the HTML.
When should I use text-based XPath in Selenium?
Text-based XPath is useful when other attributes like ID or class are missing, not unique, or keep changing. It helps you locate elements based on the exact visible text shown on the web page.
Can I find an element using partial text in Selenium?
Yes, you can find elements using a part of the text. This is helpful when the full text is too long or keeps changing slightly, but a certain part remains constant.
What are the risks of relying only on text to find elements?
Using only visible text to find elements can make tests fragile. If the text changes due to a content update or translation, your test might fail. It’s good to combine this method with other stable locators when possible.
Citations
- Finding web elements: https://www.selenium.dev/documentation/webdriver/elements/finders/
Got Questions? Drop them on LambdaTest Community. Visit now