Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Selenium can detect the existence of text in various elements by using the "text()" method in XPath. This method returns the text content of a particular node or element.

Example:

To detect if a specific text "Hello, World!" exists inside a paragraph tag, we can use the following code:

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

# wait for the element to be present
wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.XPATH, "//p[contains(text(), 'Hello, World!')]")))

if element:
   print("Text exists in the element.")
else:
   print("Text does not exist in the element.")

This code uses the WebDriverWait class to wait for the element to be present in the DOM. It then uses the XPath expression //p[contains(text(), 'Hello, World!')] to find any p element containing the specified text. Using the if statement, we can determine if the element exists and therefore if the text exists in the element.