Clear input field in selenium Python 

In this article we are going to learn how to clear the input field in Python selenium. In this code example, we will see an example of the www.google.com search input field. We will clear it with the help of selenium script.

Environments and requirements:

To run this script on your machine, you will need to install below three dependencies.
python3
ChromeDriver
Selenium.

Selenium Python script to clear input field

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get("https://google.co.in")
	search=driver.find_element(By.XPATH,"/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input")
search.send_keys('Python 3')
search.send_keys(Keys.RETURN)
driver.find_element(By.XPATH,'//*[@id="tsf"]/div[1]/div[1]/div[2]/div/div[2]/input').clear()
time.sleep(6)
driver.close()

Output:

First we open the google.com and search “Python 3”. After that we clear the input field on google.com.

Explaination:

  1. From selenium module import webdriver,by module and keys module
  2. Import time module also to wait chrome at a given seconds.
  3. Create a driver object which calls the browser
  4. Webdriver.chrome Creates a new instance of the chrome driver. Starts the service and then creates new instance of chrome driver.
  5. Now we pass the link of any site by using driver.get() method.
  6. The given site open and then we search the search field by using find element and pass the XPATH of the search bar.
  7. After that use send keys method to pass a string in input field.
  8. Then again use the driver.find_element method with clear to clear the field that is written in given element.
  9. Now use time.sleep method to hold the driver in given time and then used closed method to close the browser.