Verify the text content of a specific element on the webpage
Preconditions (3)
✅ Expected Result: The text content of the element with id 'welcome-message' is exactly 'Welcome to Example.com!'
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 def test_get_element_text(): driver = webdriver.Chrome() try: driver.get('https://example.com/welcome') wait = WebDriverWait(driver, 10) element = wait.until(EC.presence_of_element_located((By.ID, 'welcome-message'))) text = element.text assert text == 'Welcome to Example.com!', f"Expected text 'Welcome to Example.com!' but got '{text}'" finally: driver.quit() if __name__ == '__main__': test_get_element_text()
This script opens the Chrome browser and navigates to the specified URL.
It waits explicitly up to 10 seconds for the element with id 'welcome-message' to appear.
Once found, it retrieves the text content of that element.
Then it asserts that the text matches the expected string exactly.
Finally, it closes the browser to clean up.
This approach ensures the test waits properly and uses clear assertions for validation.
Now add data-driven testing with 3 different element IDs and their expected texts
.text property do in Selenium when used on a web element?.text.text property in Selenium is used to get the visible text content from a web element..text..text gets visible text [OK]element in Selenium Python?.text without parentheses.getText() and get_text() are not valid in Selenium Python. text() with parentheses is incorrect because text is a property, not a method.from selenium import webdriver from selenium.webdriver.common.by import By # Assume driver is already initialized and page loaded button = driver.find_element(By.ID, "submit-btn") print(button.text)
.text..text returnsbutton.text returns this string.element_text = driver.find_element(By.CLASS_NAME, "title").text()
.text is a property and should not have parentheses. Using .text() causes a TypeError..text property without parentheses to get visible text.getText() and get_text are invalid in Selenium Python; text() with parentheses is wrong.Pass the test and this pattern moves unknown