Selenium
WebDriver
Python
Element Identification
Text Matching

How do I find an element that contains specific text in Selenium WebDriver Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Finding elements by contained text is a common Selenium task in UI tests, especially when IDs and classes are dynamic. The usual solution is XPath with contains() or normalize-space(), but brittle selectors and timing issues cause flaky tests if you do not combine locators with proper waits. A reliable approach should prioritize stable attributes when available and use text-based selection only where necessary.

This guide covers robust text matching patterns in Selenium WebDriver with Python, including partial match, exact normalized match, waits, and ambiguity handling.

Core Sections

1. Partial text match with XPath contains()

python
1from selenium import webdriver
2from selenium.webdriver.common.by import By
3
4driver = webdriver.Chrome()
5
6el = driver.find_element(By.XPATH, "//*[contains(text(), 'Submit')]")
7el.click()

This is useful when text includes dynamic prefixes/suffixes, but it can match multiple elements.

2. Exact text match with whitespace normalization

python
1el = driver.find_element(
2    By.XPATH,
3    "//*[normalize-space(text())='Submit order']"
4)

normalize-space avoids failures caused by accidental leading/trailing spaces or multiple spaces in markup.

3. Use explicit waits to avoid race conditions

python
1from selenium.webdriver.support.ui import WebDriverWait
2from selenium.webdriver.support import expected_conditions as EC
3
4wait = WebDriverWait(driver, 10)
5button = wait.until(
6    EC.element_to_be_clickable((By.XPATH, "//button[contains(., 'Save')]") )
7)
8button.click()

Text may not be present immediately after page load; waits are mandatory for stable tests.

4. Scope text search to a container

Reduce false positives by narrowing search root.

python
modal = driver.find_element(By.CSS_SELECTOR, "div.modal-content")
confirm = modal.find_element(By.XPATH, ".//button[contains(., 'Confirm')]")
confirm.click()

Container scoping makes selectors resilient when same text appears elsewhere.

5. Handle multiple matches deterministically

python
1matches = driver.find_elements(By.XPATH, "//a[contains(., 'Details')]")
2for m in matches:
3    if m.get_attribute("href").endswith("/orders/42"):
4        m.click()
5        break

When text is duplicated, filter by additional attributes instead of relying on first match.

6. Build reusable helper functions

python
1def find_by_text(driver, tag, text, timeout=10):
2    xpath = f"//{tag}[contains(normalize-space(.), '{text}')]"
3    return WebDriverWait(driver, timeout).until(
4        EC.presence_of_element_located((By.XPATH, xpath))
5    )
6
7link = find_by_text(driver, "a", "Account settings")

Reusable helpers improve consistency across test suites.

Common Pitfalls

  • Using contains(text(), ...) on elements where visible text is nested in child nodes.
  • Skipping explicit waits and blaming locators for timing-related failures.
  • Matching broad text globally, causing clicks on wrong elements in large pages.
  • Depending on exact text in localized UIs without language-aware test data.
  • Ignoring duplicate matches and assuming first result is always correct.

Summary

To find elements containing specific text in Selenium Python, use XPath with contains() or normalized exact matching and always pair locators with explicit waits. Scope searches to meaningful containers and add secondary filters when duplicate text exists. With these practices, text-based selectors remain useful and far less flaky in real-world automation suites.

A practical way to harden this topic in real projects is to add a small operational checklist and treat it as part of your engineering standard, not a one-off fix. Start by creating one minimal failing case and one passing case that represent real input from production logs. Then automate those checks in CI so regressions are caught before release. Add lightweight instrumentation around the critical branch where this logic runs, and include structured fields that let you filter by version, environment, and error type. This gives you fast feedback when behavior changes after dependency upgrades or refactors.

For long-term maintainability on how do i find an element that contains specific text in selenium webdriver python, keep one source of truth for helper logic instead of duplicating variants across services or UI layers. Document assumptions near the code, including data format, edge-case behavior, and expected fallback policy. During code review, verify that example inputs and tests cover empty values, malformed values, and high-volume scenarios. Teams that combine explicit assumptions, repeatable tests, and basic observability typically avoid the same category of bug recurring every quarter.


Course illustration
Course illustration

All Rights Reserved.