How to Find Elements by Text in Selenium with Python

On This Page What is Find Element by Text in Selenium Python?

May 14, 2026 · 7 min read · Tool Comparison

How to Find Elements by Text in Selenium with Python

Locating elements by text in is an essential skill for web mechanisation and testing. It enables developers to find and interact with specific elements on a webpage using their visible schoolbook content, which is especially helpful when other attributes, such as IDs or stratum, are dynamical or unstable.

Read More:

What is Find Element by Text in Selenium Python?

Finding elements by textbook in Selenium with Python is a method used to identify web elements establish on their visible text. This approach is especially useful when attributes like IDs or course are dynamic or unreliable.

Typically, it leverages XPath and the contains () function to locate element containing specific text, enabling testers to interact with constituent that match the desired touchstone.

from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Remote (command_executor='https: //hub-cloud.browserstack.com/wd/hub ', desired_capabilities= {'browserName ': 'Chrome '}) driver.get (`` https: //www.browserstack.com '') factor = driver.find_element (By.XPATH, `` // * [contains (textbook (), 'Live ')] '')

This code snip demonstrates how to detect an element containing the schoolbook & # 8220; Live & # 8221; on the BrowserStack homepage using Selenium & # 8217; s XPath functionality.

The below sections enable a deep dive into notice ingredient by text using XPath in Selenium Python

Find Element by using XPath in Selenium Python

XPath in Selenium is a versatile proficiency for finding web elements using their visible textbook. This method is peculiarly useful when address with dynamic property, as it allows testers to locate factor based on their content rather than relying on potentially changing IDs or classes.

By leveraging XPath, Selenium scripts can adapt to variations in the page structure, making them more robust and maintainable.

Read More:

Some common methods of doing this are:

1. Using Exact Text Match: Locates constituent that exactly match the specified text.

driver.find_element_by_xpath (`` // * [text () ='Exact Text '] '')

2. Using the contains () Method: Helps find elements that contain a specific substring, useful for treat dynamic or fond schoolbook.

driver.find_element_by_xpath (`` // * [contains (text (), 'partial schoolbook ')] '')

3. Using normalize-space (): Removes direct and trailing spaces, ensuring accurate lucifer.

driver.find_element_by_xpath (`` // * [normalize-space (text ()) ='Exact Text '] '')

4. Using Text within Specific Tags: Allows aim element within specific HTML tags, such as headers (& lt; h1 & gt;, & lt; h2 & gt;), paragraphs (<p>), or buttons. This is useful when text appears in structured constituent.

driver.find_element_by_xpath (`` //h1 [text () ='Header Text '] '')

Find Element by Text in Selenium Python Using text () and contains () Methods

Finding elements by text in Selenium Python using text () and contains () method is a powerful proficiency for situate web ingredient found on their visible content.

These techniques are especially handy when working with active or complex web pages.

Both scheme are utilitarian in several situation. When look for an exact match, usetext(), and when deal with dynamic material or favour greater control over element choice, useincludes ().

1. Using text () Method

The text()method finds elements with an exact text match. The general syntax for finding elements by text is:

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

// * [schoolbook () ='Exact Text ']

For example, this code snip site an element on BrowserStack & # 8217; s homepage that exactly matches the text& # 8220; Live & # 8221;.

element = driver.find_element (By.XPATH, `` // * [text () ='Live '] '')

2. Using contains () Method

The contains ()method is more flexile, allowing partial textbook matches.

The general syntax for finding elements by text is:

// * [contains (schoolbook (), 'Partial Text ')]

For example, this code snippet happen elements on BrowserStack & # 8217; s site containing the tidings& # 8220; Live & # 8221;,such as & # 8220;Live for Teams& # 8221; or& # 8220; Live & # 8221;.

element = driver.find_element (By.XPATH, `` // * [contains (schoolbook (), 'Live ')] '')

Can text () and contains () method be unite for more exact element localisation?

text() and contains ()methods can be unite for more precise element locating in XPath.

Combining these methods grant developers to return more specific and precise locater, which is especially beneficial when working with dynamical text or distinguishing between alike element.

For example, this XPath manifestation observe an anchor factor on BrowserStack & # 8217; s homepage that carry the word & # 8220; Live & # 8221; and has the exact textbook & # 8220; Live & # 8221;.

element = driver.find_element (By.XPATH, `` //a [contains (schoolbook (), 'Live ') and text () ='Live '] '')

Advanced Techniques for Locating Elements by Text

Here are some of the modern technique for Locating Elements by Text:

1. Using preceding-sibling or following-sibling in XPath

This is used to find elements by their view relative to another element containing specific textbook.

For example, to place the input field that appears after the & # 8220; Username & # 8221; label on BrowserStack & # 8217; s demo site:

from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome () driver.get (`` https: //bstackdemo.com/ '') # Locate the input field following the `` Username '' label username_input = driver.find_element (By.XPATH, `` //label [schoolbook () ='Username '] /following-sibling: :input '') mark (`` Found input field: '', username_input.get_attribute (`` name '')) driver.quit ()

2. Combining Text with Former Attributes

To achieve more accurate factor identification, text content can be combined with attributes such as grade or ID.

For example, the & # 8220; Sign In & # 8221; push on BrowserStack & # 8217; s demo site can be located using the following approach:

driver = webdriver.Chrome () driver.get (`` https: //bstackdemo.com/ '') # Locate the `` Sign In '' button by combining text and class impute sign_in_button = driver.find_element (By.XPATH, `` //button [contains (text (), 'Sign In ') and @ class='btn-primary '] '') print (`` Found push: '', sign_in_button.text) driver.quit ()

How to Find Element by Text in Selenium: Example

This code certify how to find web elements on the BrowserStack website apply Selenium & # 8217; s text-based locators. It showcases two methods: an exact text lucifer use thetext()function to find the& # 8220; Live & # 8221;tie, and a partial text lucifer using thecontains ()function to site a & # 8220;Get started& # 8221; push.

The script also uses expressed postponement to ensure elements are present before interacting with them, and prints the text of the found factor to verify successful location.

from selenium significance webdriver from selenium.webdriver.common.by importation By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Initialize the WebDriver (presume Chrome) driver = webdriver.Chrome () # Navigate to BrowserStack website driver.get (`` https: //www.browserstack.com '') # Wait for the page to load wait = WebDriverWait (driver, 10) # Find element by exact text lucifer using text () full_match = wait.until (EC.presence_of_element_located ((By.XPATH, `` //a [text () ='Live '] ''))) print (`` Full match base: '', full_match.text) # Find element by fond schoolbook match using contains () partial_match = wait.until (EC.presence_of_element_located ((By.XPATH, `` //a [contains (text (), 'Get started ')] ''))) print (`` Partial match found: '', partial_match.text) # Close the browser driver.quit ()

Talk to an Expert

Best Practices to Find Element by Text in Selenium Python

Some elementary best practices can go a long way in helping find element by text in Selenium Python:

  • Use XPath withtext()for exact match andcontains ()for partial lucifer to locate element by their visible text content.
  • Implement explicit waits to ensure elements are present and seeable before attempting to interact with them.
  • Combine text() and contains ()methods for more precise ingredient location when dealing with dynamical content.
  • Utilize tools like XPath Finder or Selenium IDE to help construct accurate XPath expressions for text-based element location.
  • Prefer or other locater strategies when potential, as they are generally faster than XPath for element position.

Mutual Issues When Finding Elements by Text

Some Common Issues When Finding Elements by Text are:

  • Dynamic content laden: Elements may not be immediately available when the page loads, potentially cause error.
  • Text inconsistencies: Variations in textbook, such as capitalization differences or extra spaces, can lead to failures in locating elements.
  • Hidden or overlap elements: Text-based locators may not work if the element is hidden or overcloud by other elements on the page.

Why run Selenium Tests on Real Devices?

Running Selenium tests on real devices ascertain accurate representation of user experiences and identifies device-specific issues that ape might lose.

pass a seamless solution for this, supply access to a wide range of real devices and browsers in the cloud, enable teams to execute comprehensive cross-device testing without the need for complex infrastructure setup.

Read More:

Conclusion

Finding factor by text in Selenium with Python offers tractability when other attributes are undependable, but combining text-based locators with early scheme heighten test stability.

Running tests on existent devices furnish more accurate insights into user behavior and performance, which can be easy achieved using, proffer accession to over 20,000 existent Android and iOS devices for comprehensive testing.

Tags
83,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free