How to find an element that contains specific text in Selenium webdriver with Python?

Estimated read time 2 min read

To find an element that contains specific text in Selenium WebDriver with Python, you can use XPath or CSS selectors. Here’s an example for each approach:

Using XPath:

from selenium import webdriver

driver = webdriver.Chrome()

# Navigate to the desired webpage
driver.get("https://example.com")

# Find an element that contains specific text using XPath
element = driver.find_element_by_xpath("//*[contains(text(), 'specific text')]")

# Perform actions on the element
# ...

Using CSS selector:

from selenium import webdriver

driver = webdriver.Chrome()

# Navigate to the desired webpage
driver.get("https://example.com")

# Find an element that contains specific text using CSS selector
element = driver.find_element_by_css_selector(":contains('specific text')")

# Perform actions on the element
# ...

In both cases, you first need to initialize the WebDriver (in this example, we’re using ChromeDriver). Then, navigate to the desired webpage using the get() method.

To find the element that contains specific text, you can use the find_element_by_xpath() method with an XPath expression that uses the contains() function to match elements with the desired text. Alternatively, you can use the find_element_by_css_selector() method with the :contains() selector to achieve the same result.

Once you have found the element, you can perform further actions on it, such as clicking, sending keys, or extracting information.

Make sure to adjust the specific text and selector to match your requirements. Additionally, ensure that you have the necessary WebDriver and browser-specific drivers installed and properly configured.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply