Locating elements by text in Selenium with Python is an essential skill for web automation and testing. It enables developers to find and interact with specific elements on a webpage using their visible text content, which is especially helpful when other attributes, such as IDs or classes, are dynamic or unstable.
What is Find Element by Text in Selenium Python?
Finding elements by text in Selenium with Python is a method used to identify web elements based on their visible text. This approach is especially useful when attributes like IDs or classes are dynamic or unreliable.
Typically, it leverages XPath and the contains() function to locate elements containing specific text, enabling testers to interact with elements that match the desired criteria.
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") element = driver.find_element(By.XPATH, "//*[contains(text(), 'Live')]")
This code snippet demonstrates how to find an element containing the text “Live” on the BrowserStack homepage using Selenium’s XPath functionality.
The below sections enable a deep dive into finding element by text using XPath in Selenium Python
Find Element by using XPath in Selenium Python
XPath in Selenium is a versatile technique for finding web elements using their visible text. This method is particularly useful when dealing with dynamic attributes, as it allows testers to locate elements 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.
Some common methods of doing this are:
1. Using Exact Text Match: Locates elements 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 handling dynamic or partial text.
driver.find_element_by_xpath("//*[contains(text(),'partial text')]")
3. Using normalize-space(): Removes leading and trailing spaces, ensuring accurate matches.
driver.find_element_by_xpath("//*[normalize-space(text())='Exact Text']")
4. Using Text within Specific Tags: Allows targeting elements within specific HTML tags, such as headers (<h1>, <h2>), paragraphs (<p>), or buttons. This is useful when text appears in structured elements.
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() methods is a powerful technique for locating web elements based on their visible content.
These techniques are especially handy when working with dynamic or complex web pages.
Both strategies are useful in various situations. When searching for an exact match, use text(), and when dealing with dynamic material or prefer greater control over element selection, use includes().
1. Using text() Method
The text() method finds elements with an exact text match. The general syntax for finding elements by text is:
//*[text()='Exact Text']
For example, this code snippet locates an element on BrowserStack’s homepage that exactly matches the text “Live”.
element = driver.find_element(By.XPATH, "//*[text()='Live']")
2. Using contains() Method
The contains() method is more flexible, allowing partial text matches.
The general syntax for finding elements by text is:
//*[contains(text(),'Partial Text')]
For example, this code snippet finds elements on BrowserStack’s site containing the word “Live”, such as “Live for Teams” or “Live”.
element = driver.find_element(By.XPATH, "//*[contains(text(), 'Live')]")
Can text() and contains() methods be combined for more precise element location?
text() and contains() methods can be combined for more precise element location in XPath.
Combining these methods allows developers to generate more specific and accurate locators, which is especially beneficial when working with dynamic text or distinguishing between similar elements.
For example, this XPath expression finds an anchor element on BrowserStack’s homepage that contains the word “Live” and has the exact text “Live”.
element = driver.find_element(By.XPATH, "//a[contains(text(), 'Live') and text()='Live']")
Advanced Techniques for Locating Elements by Text
Here are some of the advanced techniques for Locating Elements by Text:
1. Using preceding-sibling or following-sibling in XPath
This is used to find elements by their position relative to another element containing specific text.
For example, to locate the input field that appears after the “Username” label on BrowserStack’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[text()='Username']/following-sibling::input") print("Found input field:", username_input.get_attribute("name")) driver.quit()
2. Combining Text with Other Attributes
To achieve more precise element identification, text content can be combined with attributes such as class or ID.
For example, the “Sign In” button on BrowserStack’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 attributes sign_in_button = driver.find_element(By.XPATH, "//button[contains(text(), 'Sign In') and @class='btn-primary']") print("Found button:", sign_in_button.text) driver.quit()
How to Find Element by Text in Selenium: Example
This code demonstrates how to find web elements on the BrowserStack website using Selenium’s text-based locators. It showcases two methods: an exact text match using the text() function to find the “Live” link, and a partial text match using the contains() function to locate a “Get started” button.
The script also uses explicit waits to ensure elements are present before interacting with them, and prints the text of the found elements to verify successful location.
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 # Initialize the WebDriver (assuming 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 match using text() full_match = wait.until(EC.presence_of_element_located((By.XPATH, "//a[text()='Live']"))) print("Full match found:", full_match.text) # Find element by partial text 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()
Best Practices to Find Element by Text in Selenium Python
Some simple best practices can go a long way in helping find element by text in Selenium Python:
- Use XPath with text() for exact matches and contains() for partial matches to locate elements by their visible text content.
- Implement explicit waits to ensure elements are present and visible before attempting to interact with them.
- Combine text() and contains() methods for more precise element location when dealing with dynamic content.
- Utilize tools like XPath Finder or Selenium IDE to help construct accurate XPath expressions for text-based element location.
- Prefer CSS selectors or other locator strategies when possible, as they are generally faster than XPath for element location.
Common Issues When Finding Elements by Text
Some Common Issues When Finding Elements by Text are:
- Dynamic content loading: Elements may not be immediately available when the page loads, potentially causing NoSuchElementException errors.
- Text inconsistencies: Variations in text, such as capitalization differences or extra spaces, can lead to failures in locating elements.
- Hidden or overlapping elements: Text-based locators may not work if the element is hidden or obscured by other elements on the page.
Why run Selenium Tests on Real Devices?
Running Selenium tests on real devices ensures accurate representation of user experiences and identifies device-specific issues that emulators might miss.
BrowserStack Automate offers a seamless solution for this, providing access to a wide range of real devices and browsers in the cloud, enabling teams to perform comprehensive cross-device testing without the need for complex infrastructure setup.
Conclusion
Finding elements by text in Selenium with Python offers flexibility when other attributes are unreliable, but combining text-based locators with other strategies enhances test stability.
Running tests on real devices provides more accurate insights into user behavior and performance, which can be easily achieved using BrowserStack’s Real Device Cloud, offering access to over 20,000 real Android and iOS devices for comprehensive testing.