How can I clear text of a textbox using Python Selenium WebDriver?

SeleniumAutomation TestingTesting Tools

We can clear text of a textbox with Selenium webdriver in Python using the clear method. First of all, we have to identify the text box with the help of any of the locators like id, css, name, class, xpath, css, or class.

Then we have to enter text into it with the help of the send_keys method. Finally, to clear it we have to use the clear method. We can verify if the text has been cleared with the help of the get_attribute method.

Syntax

l = driver.find_element_by_id('txt')
l.clear()

Let us try to clear the text from the below edit box.

Example

from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
#implicit wait
driver.implicitly_wait(0.5)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://www.tutorialspoint.com/tutor_connect/index.php")
#identify element
l = driver.find_element_by_id("txtSearchText")
l.send_keys("Selenium")
#get value entered
s= l.get_attribute("value")
print("Value after entering text: ")
print(s)
#clear text
l.clear()
t= l.get_attribute("value")
print("Value after clearing text: ")
print(t)
#close browser
driver.close()

Output

raja
Published on 07-Apr-2021 08:33:05
Advertisements