Find an element that Contains Specific Text in Python Selenium
Last Updated :
18 Sep, 2024
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.
Similar Reads
How can we Find an Element using Selenium?
Selenium is one of the most popular and powerful tools for automating web applications. Selenium is widely used for automating user interactions on a web application like clicking on a button, navigating to a web page, filling out web forms, and many more. But to interact with a web application we f
6 min read
Python Selenium - Find element by text
The technique to verify if the requirements given by the user meet with the actual software product developed is known as Software Testing. Moreover, it also checks if the final software product developed is error-free or not. Software testing can either be performed manually or with the help of sof
3 min read
find_element_by_link_text() driver method - Selenium Python
Selenium's Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out - Navigating links using get method, you might want to play more
3 min read
move_to_element method - Action Chains in Selenium Python
Seleniumâs Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and dro
2 min read
find_elements_by_link_text() driver method - Selenium Python
Selenium's Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out - Navigating links using get method, you might want to play more
2 min read
Retrieve A Specific Element In a Csv File using Python
We have given a file and our task is to retrieve a specific element in a CSV file using Python. In this article, we will see some generally used methods for retrieving a specific element in a CSV file. Retrieve a Specific Element in a CSV File Using PythonBelow are some of the ways by which we can r
2 min read
find_element(By.XPATH) driver method - Selenium Python
Selenium's Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out - Navigating links using the get method , you might want to play
3 min read
How to check if an element exists with Python Selenium?
Selenium is one of the most powerful and widely used tools for web automating web applications. Whether you're a software developer or a QA tester, Selenium is an important tool to have in your toolkit. Selenium is widely used for automating user interactions like clicking buttons, filling out the f
7 min read
Close specific Web page using Selenium in Python
Prerequisites: Selenium Basics, Selenium close() and quit() Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc
2 min read
Select rows that contain specific text using Pandas
While preprocessing data using pandas dataframe there may be a need to find the rows that contain specific text. Our task is to find the rows that contain specific text in the columns or rows of a dataframe in pandas. Dataset in use: jobAge_RangeSalaryCredit-RatingSavingsBuys_HoneOwnMiddle-agedHighF
4 min read