Explain Codes LogoExplain Codes Logo

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

python
xpath
selenium
webdriver
Anton ShumikhinbyAnton Shumikhin·Feb 12, 2025
TLDR

Quickly find elements carrying specific text in Selenium WebDriver using Python with the help of XPath and the contains() function:

element = driver.find_element_by_xpath("//*[contains(text(),'YourText')]")

This snippet of code locates the element encapsulating "YourText". Simply replace "YourText" with the actual string you're trying to locate.

Refine XPath search using HTML tags

A strategic XPath query narrows down searches to the pertinent HTML tags, circumventing a comprehensive DOM search:

# Why read the whole book when you're only interested in one page? button = driver.find_element_by_xpath("//button[contains(., 'YourButtonName')]")

XPath scanning the <button> elements is akin to using 'Ctrl+F' in a document instead of reading everything.

Steer clear of vague text

Aiming for a broad text query, like so:

# This might get you ALL the coffee shops in the city, not just your favourite one elements = driver.find_elements_by_xpath("//*[contains(., 'CommonText')]")

A common misstep is to generalize your text query too much, leading to a traffic jam of unwanted elements.

Cater to unexpected text variations with XPath functions

Handling text that sport whitespace or varying case can be a curveball:

# Ignore the 'messy hair' of a text div_element = driver.find_element_by_xpath("//div[normalize-space()='YourText']") # Looking for 'Tom', but not sure if it's 'Tom', 'tom', or 'TOM'? div_element = driver.find_element_by_xpath("//*[contains(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'yourtext')]")

These XPath functions clean up any text irregularities and provide a beeline to the required element.

Harness Page Object Model for organized locators

Page Object Model (POM) is your kind ally in maintaining large projects and managing dynamic content. It is great at keeping WebElement locators tidy and accessible:

class MyPageObject: # Taking care of the rooms in your house (read: WebElements) MY_BUTTON = (By.XPATH, "//button[contains(., 'My Button')]") def __init__(self, driver): self.driver = driver # Room service? Your button is ready, sir. def get_my_button(self): return self.driver.find_element(*self.MY_BUTTON)

The Page Object Model lends easy debugging and quick updates via @FindBy and similar locator strategies.

Narrow down search with class and attribute filters

When same text exists across multiple elements, XPath shines by aiming the spotlight towards specifics, just like a narrowing search filter:

# Shopping for 'blue leather jackets' among a plethora of 'jackets' element = driver.find_element_by_xpath("//button[contains(@class, 'btn-primary') and contains(text(),'Submit')]")

Take precaution for performance

Speed matters! Your element locator choice can save precious seconds, especially on large web pages:

# Why take the stairs when there's an escalator? elements = driver.find_elements_by_xpath("//button[contains(., 'My Button')]")

This strategy ensures a swift and direct pinpoint of button elements, ditching slower selectors like //*.

Watch out for tricky nested elements

Nested elements can be a hiccup while choosing elements. Pay heed to the element hierarchy:

# Wait, is it the dinner you like or just the sauce? parent = driver.find_element_by_xpath("//*[contains(text(), 'YourText') and not(.//*[contains(text(), 'YourText')])]")

Use pattern matching for dynamic content

If the text is a moving target, XPath functions like starts-with() or ends-with() cast a wider net:

# Does it start with 'Hello' or ends with 'Goodbye'? variable_element = driver.find_element_by_xpath("//*[starts-with(text(), 'Welcome')]")