0
0
Selenium Pythontesting~5 mins

Clearing input fields in Selenium Python

Choose your learning style9 modes available
Introduction

Clearing input fields helps remove any existing text before typing new information. This ensures tests enter data correctly without leftover text.

Before entering a username in a login form to avoid mixing old and new text.
When testing a search box to clear previous search terms before a new search.
In a form with multiple steps, clearing fields before updating values.
When verifying that clearing a field works as expected in the application.
Syntax
Selenium Python
element.clear()

This method clears the text from an input or textarea element.

Make sure the element is interactable before calling clear(), or it may cause errors.

Examples
Finds the search box by its ID and clears any text inside.
Selenium Python
search_box = driver.find_element(By.ID, "search")
search_box.clear()
Clears the username input field found by its name attribute.
Selenium Python
username_field = driver.find_element(By.NAME, "username")
username_field.clear()
Sample Program

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 value
print("Before clear:", input_field.get_attribute("value"))

# Clear the input field
input_field.clear()

# Print value after clearing
print("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.