0
0
Selenium Pythontesting~15 mins

Getting element attributes in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify the placeholder attribute of the search input field
Preconditions (1)
Step 1: Locate the search input field by its id 'search-box'
Step 2: Get the value of the 'placeholder' attribute of the search input field
Step 3: Verify that the placeholder text is 'Search here...'
✅ Expected Result: The placeholder attribute of the search input field should be 'Search here...'
Automation Requirements - Selenium with Python
Assertions Needed:
Assert that the placeholder attribute value equals 'Search here...'
Best Practices:
Use explicit waits to ensure the element is present before accessing attributes
Use By.ID locator for the search input field
Use assert statements for verification
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

# Initialize the Chrome driver
with webdriver.Chrome() as driver:
    driver.get('https://example.com')  # Replace with actual URL

    # Wait until the search input field is present
    wait = WebDriverWait(driver, 10)
    search_input = wait.until(EC.presence_of_element_located((By.ID, 'search-box')))

    # Get the placeholder attribute
    placeholder_text = search_input.get_attribute('placeholder')

    # Assert the placeholder text
    assert placeholder_text == 'Search here...', f"Expected placeholder to be 'Search here...' but got '{placeholder_text}'"

    print('Test passed: Placeholder attribute is correct.')

This script uses Selenium with Python to automate the manual test case.

First, it opens the browser and navigates to the homepage URL.

It waits explicitly for the search input field with id 'search-box' to be present to avoid timing issues.

Then, it retrieves the 'placeholder' attribute value using get_attribute.

Finally, it asserts that the placeholder text matches the expected value 'Search here...'. If the assertion passes, it prints a success message.

This approach ensures the test is reliable and clear.

Common Mistakes - 3 Pitfalls
Using time.sleep() instead of explicit waits
Using an incorrect locator like XPath with absolute path
Not checking if the element exists before getting attribute
Bonus Challenge

Now add data-driven testing to verify placeholder attributes for three different input fields with ids 'search-box', 'email-input', and 'username-input' and their expected placeholders.

Show Hint