How to clear input text field in Selenium Python?

Selenium Python – Clear input text field

In this tutorial, you will learn how to clear an input text field, or remove any value entered by a user in the input text field in Selenium Python.

To clear the value present in an input text field in Selenium Python, you can use clear() method of the element object.

Steps to clear input text field

  1. Find the input text field element in the web page using driver.find_element() method.
  2. Call clear() method on the input text box element.
input_text_element.clear()

Example

In the following example, we initialize a Chrome webdriver, navigate to a specific URL: https://pythonexamples.org/tmp/selenium/index-36.html that contains a form element with a couple of input text boxes, take the screenshot, clear the value present in the input text field whose id is "fname", and then again take the screenshot of the page.

<html>
 <body>
  <h3>My Form</h3>
  <form action="">
    <label for="fname">First name:</label>
    <input type="text" id="fname" name="fname" value="Hero"><br><br>
    <label for="lname">Last name:</label>
    <input type="text" id="lname" name="lname" value="Super"><br><br>
    <input type="submit" value="Submit">
  </form>
 </body>
</html>
Copy

Python Program

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By

# Setup chrome driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
driver.set_window_size(500, 500)

# Navigate to the url
driver.get('https://pythonexamples.org/tmp/selenium/index-36.html')

# Take a screenshot of the webpage
driver.save_screenshot("screenshot-1.png")

# Find input text box
input_text_fname = driver.find_element(By.ID, 'fname')

# Clear the vlaue in input text field
input_text_fname.clear()

# Take a screenshot of the webpage
driver.save_screenshot("screenshot-2.png")

# Close the driver
driver.quit()
Copy

screenshot-1.png – Before clearing input text field

Python Selenium - Clear input text field - Before screenshot

screenshot-2.png – After clearing input text field

Python Selenium - Clear input text field - After screenshot

Summary

In this Python Selenium tutorial, we have given instructions on how to clear an input text field, using clear() method of the input text element object.

Related Tutorials

Quiz on Selenium

Q1. What is a web driver in Selenium Python?

Not answered

Q2. What is the method used to find web elements in Selenium Python?

Not answered

Q3. Which of the following is not a method to wait for a web element to load in Selenium Python?

Not answered

Q4. Which of the following is not a commonly used assertion method in Selenium Python?

Not answered

Q5. Which of the following is not a commonly used web element locator in Selenium Python?

Not answered
Code copied to clipboard successfully 👍