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
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read