This script opens a simple page with an input field that has text. It prints the value before and after clearing the field to show the effect of clear().
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
# Setup WebDriver (make sure the driver executable is in PATH)
driver = webdriver.Chrome()
# Open a simple page with an input field
html = '''
<html>
<body>
<input type="text" id="input1" value="Hello World">
</body>
</html>
'''# Load the HTML content
driver.get("data:text/html;charset=utf-8," + html)
# Locate the input field
input_field = driver.find_element(By.ID, "input1")
# Print current valueprint("Before clear:", input_field.get_attribute("value"))
# Clear the input field
input_field.clear()
# Print value after clearingprint("After clear:", input_field.get_attribute("value"))
# Close the browser
driver.quit()
OutputSuccess
Important Notes
Sometimes, clearing may not work if the input is read-only or disabled.
Use explicit waits to ensure the element is ready before clearing.
Summary
Use clear() to remove existing text from input fields.
Clearing helps avoid mixing old and new input during tests.
Always locate the element correctly and ensure it is interactable before clearing.
Practice
(1/5)
1. What is the main purpose of using clear() method on an input field in Selenium?
easy
A. To remove any existing text before entering new text
B. To submit the form automatically
C. To locate the input field on the page
D. To check if the input field is visible
Solution
Step 1: Understand the clear() method
The clear() method removes any existing text inside an input field.
Step 2: Purpose in testing
Clearing ensures old text does not mix with new input, avoiding test errors.
Final Answer:
To remove any existing text before entering new text -> Option A
Quick Check:
clear() removes text = D [OK]
Hint: Remember: clear() empties input fields before typing [OK]
Common Mistakes:
Thinking clear() submits the form
Confusing clear() with locating elements
Assuming clear() checks visibility
2. Which of the following is the correct syntax to clear an input field stored in variable input_box in Selenium Python?
easy
A. input_box.clear()
B. input_box.clear
C. clear(input_box)
D. input_box.clear_text()
Solution
Step 1: Identify method call syntax
In Python, methods are called with parentheses, so clear() must have () after the method name.
Step 2: Match correct method name and usage
The correct method is clear() called on the element variable: input_box.clear().
Final Answer:
input_box.clear() -> Option A
Quick Check:
Method call needs () = C [OK]
Hint: Method calls need parentheses () in Python [OK]
Common Mistakes:
Omitting parentheses after clear
Using a non-existent method like clear_text
Trying to call clear as a standalone function
3. What will be the content of the input field after executing this code snippet?