Clear input text field in Selenium
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
- Find the input text field element in the web page using
driver.find_element()
method. - 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: /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>
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('/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()
screenshot-1.png - Before clearing input text field
screenshot-2.png - After clearing input text field
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.