How do I send a DELETE keystroke to a text field using Selenium with Python?

SeleniumAutomation TestingTesting Tools

We can send a DELETE keystroke to a text field using Selenium webdriver with Python. First of all, we have to identify the text field with the help of any locators like xpath, css, id, and so on.

We can enter a text in the text field with the send_keys method. The value to be entered is passed as parameter to the method. To delete a key, we can pass Keys.BACKSPACE as a parameter to the send_keys method.

Syntax

l = driver.find_element_by_id("gsc−i−id1")
l.send_keys("Sel")
l.send_keys(Keys.BACKSPACE)

To delete all the keys entered simultaneously, we have to pass CTRL+A and BACKSPACE as parameters to the send_keys method.

Syntax

l = driver.find_element_by_id("gsc−i−id1")
l.send_keys("Sel")
l.send_keys(Keys.CONTROL + 'a', Keys.BACKSPACE)

Also, to use the Keys class, we have to add the import statement from selenium.webdriver.common.keys import Keys in our code.

Example

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
#set geckodriver.exe path
driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify element and enter text
l = driver.find_element_by_id("gsc−i−id1")
l.send_keys("Sel")
#delete a key
l.send_keys(Keys.BACKSPACE)
print("Value after deleting a single key")
print(l.get_attribute('value'))
#wait for some time
time.sleep(0.8)
#delete all keys at once
l.send_keys(Keys.CONTROL + 'a', Keys.BACKSPACE)
print("Value after deleting entire key")
print(l.get_attribute('value'))
#close driver session
driver.quit()

Output

raja
Published on 02-Feb-2021 11:34:48
Advertisements