Clear text from an input field on a web form
Preconditions (2)
✅ Expected Result: The input field with id 'username' is empty after clearing
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.
Now add data-driven testing with 3 different input fields to clear: 'username', 'email', and 'phone'.
clear() method on an input field in Selenium?clear() methodclear() method removes any existing text inside an input field.input_box in Selenium Python?clear() must have () after the method name.clear() called on the element variable: input_box.clear().input_box = driver.find_element(By.ID, "username")
input_box.send_keys("hello")
input_box.clear()
input_box.send_keys("world")clear() removes it, then "world" is typed.input_box = driver.find_element(By.NAME, "email") input_box.clear
input_box.clear without parentheses, so the method is not called.input_box.clear().input_box.text is usually empty for input fields; the actual content is in the 'value' attribute.input_box.get_attribute('value') returns the current text inside the input field.clear() to remove it.Pass the test and this pattern moves unknown