0
0
Selenium Pythontesting~15 mins

Clearing input fields in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Clear text from an input field on a web form
Preconditions (2)
Step 1: Open the web page with the input field
Step 2: Locate the input field by its id 'username'
Step 3: Clear the existing text from the input field
Step 4: Verify that the input field is empty
✅ Expected Result: The input field with id 'username' is empty after clearing
Automation Requirements - Selenium with Python
Assertions Needed:
Verify the input field is empty after clearing
Best Practices:
Use explicit waits to ensure the input field is present before interacting
Use By.ID locator for the input field
Use clear() method to clear the 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/login')  # Replace with actual URL

    # Wait until the input field is present
    wait = WebDriverWait(driver, 10)
    input_field = wait.until(EC.presence_of_element_located((By.ID, 'username')))

    # Clear the input field
    input_field.clear()

    # Verify the input field is empty
    assert input_field.get_attribute('value') == '', 'Input field is not empty after clearing'

This script opens the web page and waits explicitly for the input field with id 'username' to be present. It uses clear() method to remove any existing text from the input field. Then it asserts that the input field's value attribute is empty, confirming the field was cleared successfully. Using explicit waits ensures the element is ready before interaction, which avoids errors. The with statement ensures the browser closes automatically after the test.

Common Mistakes - 3 Pitfalls
Using time.sleep() instead of explicit waits
Using incorrect locator like By.CLASS_NAME with a generic class
{'mistake': 'Not verifying the input field is empty after clearing', 'why_bad': 'The test might pass even if the field was not cleared properly.', 'correct_approach': "Add an assertion to check the input field's value is empty."}
Bonus Challenge

Now add data-driven testing with 3 different input fields to clear: 'username', 'email', and 'phone'.

Show Hint