Open In App

Find an element that Contains Specific Text in Python Selenium

Last Updated : 18 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Selenium WebDriver, one of the key tasks when automating web applications is finding elements that contain specific text. This is especially useful when we need to verify that certain text is displayed on a page or interact with elements based on the text they contain. While Selenium provides multiple ways to locate elements, the most effective methods for finding elements by their text are using XPath or CSS selectors. In this article, we’ll walk through how to find an element that contains specific text using Selenium WebDriver.

Find Elements by Text in Selenium:

Selenium allows us to find elements using several different strategies, such as by their ID, class, name, or tag. However, when our goal is to find an element based on the text inside it, XPath and CSS selectors become more relevant. These methods allow us to search for elements that contain specific text, which isn’t possible with simpler locator methods like find_element_by_id or find_element_by_class_name.

1. Using find_element_by_xpath();

XPath, which stands for XML Path Language, is a versatile method that can be used to navigate and find elements in both XML and HTML documents. In Selenium, we can use XPath to search for elements that contain specific text.

Example:

Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# Set up the WebDriver 
driver = webdriver.Chrome()

try:
    
    driver.get("https://example.com")
    time.sleep(5)  

    # Wait until the <h1> element containing the specific text is present
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//h1[text()='Example Domain']"))
    )

    # Print the text of the found element
    print("Element text:", element.text)
    time.sleep(5)  

except Exception as e:
    print("An error occurred:", e)

finally:
    # Close the browser
    driver.quit()

Output:

2. Using find_element_by_css_selector():

While XPath is the go-to method for finding elements by text, CSS selectors can also be used. CSS selectors are great for finding elements based on their structure or attributes. However, when it comes to finding elements by their text content, CSS is less useful because CSS alone does not directly support searching by text content in most browsers.

Example:

Python
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

try:
    # Open the desired webpage
    driver.get("https://example.com")
    time.sleep(5)

    try:

        element = driver.find_element(By.CSS_SELECTOR, 'h1')

        # Print the text of the located element
        print(f"Element text: {element.text}")


    except NoSuchElementException:
        # Handle the case where the element is not found
        print("Element with the specified CSS selector was not found.")

finally:
    # Close the browser
    driver.quit()

Output:

Example Code Snippet:

Here’s a example that shows how to use Selenium WebDriver to find and interact with an element containing specific text:

Python
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

# Set up the WebDriver (you may need to specify the path to your WebDriver executable)
driver = webdriver.Chrome()

try:
    # Navigate to the website
    driver.get("https://example.com")

    # Get and print the current window handle
    current_window_handle = driver.current_window_handle
    print(f"Current window handle: {current_window_handle}")

    # Get and print the page title
    page_title = driver.title
    print(f"Page title: {page_title}")

    # Check if the text we expect is on the page
    try:
        # Wait for an element with the expected text to be present
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.TAG_NAME, "h1"))
        )
        print(f"Element text: {element.text}")
    except TimeoutException:
        print("An error occurred: The element was not found on the page within the time limit.")

finally:
    # Close the browser window
    driver.quit()

Output:


Best Practices:

1. Use Specific Locators: It’s better to be as specific as possible when locating elements. For example, rather than using //* to find any element, we can narrow down the search by specifying the tag, like //div or //span. This reduces the chance of matching unintended elements and improves performance.

2. Manage Dynamic Content: If the content on the page is dynamic (for example, it loads later or changes frequently), we might need to wait until the element is available using WebDriverWait. This ensures that our script doesn’t fail if the element hasn’t yet loaded.

3. Use Descriptive XPath Queries: We can make our XPath locators more reliable by combining text with other attributes, such as class or id. This adds specificity and reduces the likelihood of errors.

For example:

Python
element = driver.find_element_by_xpath("//button[@class='btn'][contains(text(), 'Submit')]")

4. Cross-browser Testing: XPath behavior might vary across different browsers. Ensure that our solution works consistently by testing in all browsers that our application supports.

Conclusion

By following best practices—using specific locators, managing dynamic content with WebDriverWait, writing descriptive XPath queries, and ensuring cross-browser compatibility—you can enhance the accuracy, efficiency, and reliability of your Selenium tests. Properly locating elements ensures smooth automation, leading to more robust and maintainable test suites.


Next Article
Practice Tags :

Similar Reads