How to Find Element by Text using Xpath Selenium: Example
By Jash Unadkat, Community Contributor - November 15, 2024
Locating elements is the most fundamental step in web test automation. QAs can locate elements in multiple ways.
Selenium users, especially, need to be proficient in using different locator strategies to identify web elements. This is the first step of running any automated test because test scripts must identify the element they have to interact with.
Sometimes, web developers categorize web elements with identical class names or IDs. If the WebDriver cannot locate a certain web element, this can result in failed tests.
In such cases, QA engineers can locate the element using text visible on-screen corresponding to that particular web element. This is possible using the Find Element by Text method using the Xpath locator.
What is XPath Contains?
XPath contains() is a function used in XML and HTML to locate web elements that include specific text or partial attribute values, making it highly versatile for web automation.
By allowing partial matches, contains() is useful when dealing with dynamic elements where the text or attributes may not be entirely predictable. This function helps testers and developers identify elements even when certain attributes change, improving the efficiency and adaptability of automated test scripts in tools like Selenium.
Pro Tip: Want to dive deeper into Selenium implementation on BrowserStack with free interactive courses and lab exercises? Visit Test University.
Find Element by Text in Selenium using text() and contains methods
Here is a fundamental understanding of text() and contains() methods:
- text(): A built-in method in Selenium WebDriver that is used with XPath locator to locate an element based on its exact text value.
Example: //*[ text() = ‘Get started free’ ] - contains(): Similar to the text() method, contains() is another built-in method used to locate an element based on partial text match.
For example, if we need to locate a button that has “Get started free” as its text, it can be located using the following line of code with Xpath.
Example: //*[ contains (text(), ‘Get started’ ) ]
Follow-up Read: Quick XPath Locators Cheat Sheet
How to Find Element by Text in Selenium: Example
Here is a demonstration on locating the CTA using the text() method with Selenium Xpath.
Step 1. Launch the Chrome browser
Step 2. Navigate to BrowserStack’s website
Step 3. Locate the CTA with the text value ‘Get started free’ using the XPath text() method.
The code to locate the test using Selenium XPATH method:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class Match{ public static void main(String[] args) { System.setProperty("<Path of the ChromeDriver>"); WebDriver driver = new ChromeDriver(); String url = "https:/browserstack.com”; driver.get(url); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Locating element with text() WebElement e = driver.findElement(By.xpath("//*[text()='Get started free']")); System.out.println("Element with text(): " + e.getText() ); driver.quit(); } }
Similarly, QAs can locate the same CTA button by partial text match using the contains() method. The code above remains the same except for the method to locate the element.
Learn More: CSS Selector to locate web elements
Replace the text() method with the following code:
// located element with contains() WebElement m = driver.findElement (By.xpath ("//*[contains(text(),'Get started ')]"));
The method above will locate the “Get started free” CTA based on the partial text match made against the string ‘Get started’.
Also Read: Selenium WebElement Commands
Conclusion
As mentioned earlier, for successful test automation, testing the target web elements is of utmost importance. To do so, QA engineers must be able to use different locator strategies. The Selenium find element by text method can prove useful for QAs seeking to re-execute failed tests by locating elements accurately based on its text.
Bear in mind that Selenium tests must be run on a real device cloud to get completely accurate results. BrowserStack’s cloud Selenium grid of 3500+ real browsers and devices allows testers to automated visual UI tests in real user conditions. Simply sign up for free, select a device-browser-OS combination, and start running tests.
Run Selenium Tests on Real Device Cloud for Free
Useful Resources for Selenium
Methods, Classes, and Commands
- Selenium Commands every Developer or Tester must know
- Selenium WebElement Commands
- Desired Capabilities in Selenium Webdriver
- Assert and Verify Methods in Selenium
- Understanding System setProperty in Selenium
- Select Class in Selenium : How to select a value in dropdown list?
- SendKeys in Selenium WebDriver
- getAttribute() method in Selenium: What, Why, and How to use
- How does Selenium isDisplayed() method work?
- findElement vs findElements in Selenium
- Types of Listeners in Selenium (with Code Examples)
- How to set Proxy in Firefox using Selenium WebDriver?
Configuration
- How to set up Selenium on Visual Studio
- How to configure Selenium in Eclipse
- Maven Dependency Management with Selenium
- How to Build and Execute Selenium Projects
XPath
- How to use XPath in Selenium?
- How to find element by XPath in Selenium with Example
- Top Chrome Extensions to find Xpath in Selenium
Locators and Selectors
- Locators in Selenium: A Detailed Guide
- CSS Selector in Selenium: Locate Elements with Examples
- How to Create Object Repository in Selenium
Waits in Selenium
- Wait Commands in Selenium C and C#
- Selenium Wait Commands: Implicit, Explicit, and Fluent Wait
- Understanding Selenium Timeouts
- Understanding ExpectedConditions in Selenium
- Understanding Role of Thread.sleep() in Selenium
Frameworks in Selenium
- Data Driven Framework in Selenium
- Implementing a Keyword Driven Framework for Selenium: A Practical Guide
- Hybrid Framework in Selenium
Miscellaneous
- How to create Selenium test cases
- How to set Proxy in Selenium?
- Difference between Selenium Standalone server and Selenium server
- Exception Handling in Selenium WebDriver
- How to use JavascriptExecutor in Selenium
- How to run your first Selenium test script
- Parallel Testing with Selenium
Best Practices, Tips and Tricks
- Top 5 Challenges Faced During Automation Selenium Testing
- 5 Selenium tricks to make your life easier
- 6 Things to avoid when writing Selenium Test Scripts
- Best Practices for Selenium Test Automation
- Why you should pay attention to flaky Selenium tests
- How to start with Selenium Debugging
- How to make your Selenium test cases run faster
- How to upgrade from Selenium 3 to Selenium 4
- Why you should move your testing to a Selenium Cloud?
Design Patterns in Selenium: Page Object Model and Page Factory
- Design Patterns in Selenium
- Page Object Model and Page Factory in Selenium
- Page Object Model and Page Factory in Selenium C#
- Page Object Model in Selenium and JavaScript
- Page Object Model and Page Factory in Selenium Python
Action Class
- How to handle Action class in Selenium
- How to perform Mouse Hover Action in Selenium
- Understanding Click Command in Selenium
- How to perform Double Click in Selenium?
- How to Drag and Drop in Selenium?
- How to Scroll Down or Up using Selenium Webdriver
- How To verify Tooltip Using Selenium
TestNG and Selenium
- Database Testing using Selenium and TestNG
- How to use DataProvider in Selenium and TestNG?
- All about TestNG Listeners in Selenium
- How to run parallel test cases in TestNG
- How to use TestNG Reporter Log in Selenium: Tutorial
- Prioritizing tests in TestNG with Selenium
JUnit and Selenium
- Understanding JUnit assertions for Selenium Testing with Examples
- How to run JUnit Parameterized Test in Selenium
- How to write JUnit test cases
- JUnit Testing Tutorial: JUnit in Java
- How to create JUnit Test Suite? (with Examples)
Use Cases
- Handling Login Popups in Selenium WebDriver and Java
- How to Launch Browser in Selenium
- How to handle Alerts and Popups in Selenium?
- How to get Selenium to wait for a page to load
- How to Find Element by Text in Selenium: Tutorial
- How to Read/Write Excel Data using Apache POI Selenium
- How to handle Captcha in Selenium
- How to handle multiple windows in Selenium?
- How to handle Multiple Tabs in Selenium
- How to find broken links in Selenium
- How to handle Cookies in Selenium WebDriver
- How to handle iFrame in Selenium
- How to handle Web Tables in Selenium
- How To Validate Text in PDF Files Using Selenium Automation
- Get Current URL in Selenium using Python: Tutorial
Types of Testing with Selenium
- Different Testing Levels supported by Selenium
- How to perform UI Testing with Selenium
- Regression Testing with Selenium: Tutorial
- UI Automation using Python and Selenium: Tutorial
- How to Run Visual Tests with Selenium: Tutorial
- How to perform ETL Automation using Selenium
- Cross Browser Testing in Selenium : Tutorial