0
0
Selenium Pythontesting~15 mins

Getting element text in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify the text content of a specific element on the webpage
Preconditions (3)
Step 1: Open the web browser
Step 2: Navigate to the test webpage URL 'https://example.com/welcome'
Step 3: Locate the element with id 'welcome-message'
Step 4: Read the text content of this element
Step 5: Compare the text content with the expected text 'Welcome to Example.com!'
✅ Expected Result: The text content of the element with id 'welcome-message' is exactly 'Welcome to Example.com!'
Automation Requirements - Selenium with Python
Assertions Needed:
Assert that the text retrieved from the element with id 'welcome-message' matches 'Welcome to Example.com!'
Best Practices:
Use explicit waits to wait for the element to be present before accessing text
Use By.ID locator strategy for locating the element
Use assert statements for verification
Close the browser after test execution
Automated Solution
Selenium 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

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.

Common Mistakes - 4 Pitfalls
Using time.sleep() instead of explicit waits
{'mistake': 'Using incorrect locator like By.CLASS_NAME with a wrong class', 'why_bad': "The element won't be found, causing NoSuchElementException.", 'correct_approach': 'Use By.ID with the exact id value for reliable element location.'}
Not closing the browser after test
Comparing element.text with partial or incorrect expected text
Bonus Challenge

Now add data-driven testing with 3 different element IDs and their expected texts

Show Hint