[python] Clear text from textarea with selenium

I've got some tests where I'm checking that the proper error message appears when text in certain fields are invalid. One check for validity is that a certain textarea element is not empty.

If this textarea already has text in it, how can I tell selenium to clear the field?

something like:

driver.get_element_by_id('foo').clear_field()

This question is related to python selenium selenium-webdriver

The answer is


driver.find_element_by_xpath("path").send_keys(Keys.CONTROL + u'\ue003') worked great with FireFox

  • u'\ue003' is a BACK_SPACE for those like me - never remembering it)

I ran into a field where .clear() did not work. Using a combination of the first two answers worked for this field.

from selenium.webdriver.common.keys import Keys

#...your code (I was using python 3)

driver.find_element_by_id('foo').send_keys(Keys.CONTROL + "a");
driver.find_element_by_id('foo').send_keys(Keys.DELETE);

It is general syntax

driver.find_element_by_id('Locator value').clear();
driver.find_element_by_name('Locator value').clear();

for java

driver.findelement(By.id('foo').clear();

or

webElement.clear();

If this element is a text entry element, this will clear the value.


In the most recent Selenium version, use:

driver.find_element_by_id('foo').clear()

In my experience, this turned out to be the most efficient

driver.find_element_by_css_selector('foo').send_keys(u'\ue009' + u'\ue003')

We are sending Ctrl + Backspace to delete all characters from the input, you can also replace backspace with delete.

EDIT: removed Keys dependency


With a simple call of clear() it appears in the DOM that the corresponding input/textarea component still has its old value, so any following changes on that component (e.g. filling the component with a new value) will not be processed in time.

If you take a look in the selenium source code you'll find that the clear()-method is documented with the following comment:

/** If this element is a text entry element, this will clear the value. Has no effect on other elements. Text entry elements are INPUT and TEXTAREA elements. Note that the events fired by this event may not be as you'd expect. In particular, we don't fire any keyboard or mouse events. If you want to ensure keyboard events are fired, consider using something like {@link #sendKeys(CharSequence...)} with the backspace key. To ensure you get a change event, consider following with a call to {@link #sendKeys(CharSequence...)} with the tab key. */

So using this helpful hint to clear an input/textarea (component that already has a value) AND assign a new value to it, you'll get some code like the following:

public void waitAndClearFollowedByKeys(By by, CharSequence keys) {
    LOG.debug("clearing element");
    wait(by, true).clear();
    sendKeys(by, Keys.BACK_SPACE.toString() + keys);
}

public void sendKeys(By by, CharSequence keysToSend) {
    WebElement webElement = wait(by, true);
    LOG.info("sending keys '{}' to {}", escapeProperly(keysToSend), by);
    webElement.sendKeys(keysToSend);
    LOG.info("keys sent");
}

private String escapeProperly(CharSequence keysToSend) {
    String result = "" + keysToSend;
    result = result.replace(Keys.TAB, "\\t");
    result = result.replace(Keys.ENTER, "\\n");
    result = result.replace(Keys.RETURN, "\\r");

    return result;
}

Sorry for this code being Java and not Python. Also, I had to skip out an additional "waitUntilPageIsReady()-method that would make this post way too long.

Hope this helps you on your journey with Selenium!


Option a)

If you want to ensure keyboard events are fired, consider using sendKeys(CharSequence).

Example 1:

 from selenium.webdriver.common.keys import Keys
 # ...
 webElement.sendKeys(Keys.CONTROL + "a");
 webElement.sendKeys(Keys.DELETE);

Example 2:

 from selenium.webdriver.common.keys import Keys
 # ...
 webElement.sendKeys(Keys.BACK_SPACE); //do repeatedly, e.g. in while loop

WebElement

There are many ways to get the required WebElement, e.g.:

  • driver.find_element_by_id
  • driver.find_element_by_xpath
  • driver.find_element

Option b)

 webElement.clear();

If this element is a text entry element, this will clear the value.

Note that the events fired by this event may not be as you'd expect. In particular, we don't fire any keyboard or mouse events.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception?

Examples related to selenium-webdriver

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? Scrolling to element using webdriver? Only local connections are allowed Chrome and Selenium webdriver Check if element is clickable in Selenium Java