How do I send a DELETE keystroke to a text field using Selenium with Python?
You can use Ctr+a
to highlight the text and remove it by BACKSPACE
:
from selenium.webdriver.common.keys import Keys
element.send_keys(Keys.CONTROL, 'a')
element.send_keys(Keys.BACKSPACE)
You need to use Keys.BACKSPACE
instead of Keys.DELETE
if you want to delete a character before the cursor. Keys.DELETE
is used to delete a character after the cursor.
Be sure you are using the following import:
from selenium.webdriver.common.keys import Keys
In python if element.clear() (doesn't fire onChange in react) doesn't work try this.
def clear_text(element):
length = len(element.get_attribute('value'))
element.send_keys(length * Keys.BACKSPACE)