203

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()
Isaac
  • 9,372
  • 4
  • 28
  • 31
  • 7
    I found it driver.get_element_by_id('foo').clear() – Isaac Oct 11 '11 at 20:35
  • 2
    9 years later, and it's still surprisingly common to use the obvious thing `input_field.clear` and have it... not `clear` the `input_field`. For no good reason. St Isidore help us. – phtrivier Feb 17 '21 at 17:24

17 Answers17

293
driver.find_element_by_id('foo').clear()
Isaac
  • 9,372
  • 4
  • 28
  • 31
  • 16
    This does not work for me in the most recent Selenium version. – Union find Sep 29 '14 at 00:51
  • 5
    youp chromedriver also breaks on this one. Fenix answer works everywhere – norbertas.gaulia Sep 08 '15 at 18:10
  • 2
    It may be an issue with conflicting selenium and chromedriver versions. It seems unlikely that the devs would remove this functionality from chromedriver deliberatly. – Isaac Sep 12 '15 at 15:25
  • 8
    At the moment this answer does not work correctly in React apps as clear will not cause the React onChange function to fire. Thus your input will be cleared and tests will move on and the state of your component will remain as it was before. [react issue](https://github.com/facebook/react/issues/8004), [selenium issue](https://github.com/SeleniumHQ/selenium/issues/1841) – ncrmro Apr 24 '17 at 12:49
  • 3
    @ncrmro 3 years later it looks like this still does not work – tread Apr 03 '20 at 15:44
  • Works with Selenium Java 0:) – Zoette May 07 '20 at 00:25
  • Still does not work with python + chrome + selenium combinition. – lifeisshubh Jul 22 '21 at 10:11
  • This won't work with React or any other input with sophisticated event handlers – libby Feb 23 '22 at 01:25
143

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.

Fenix
  • 2,271
  • 1
  • 16
  • 24
  • 8
    When using CTRL+'a' consider situation when test will be running on MacOS (other keyboard shortcuts). Btw -good suggestion, solved my issue. – Outside_Box Jan 15 '18 at 11:17
  • 2
    My problem solved by the "Keys.BACK_SPACE". I just capture the search test field, run .click() then inside a for loop run the code. it removes all the charterers the search field previously had. then send new value to the search field. Just .clear() function was not working for me. – Noman_ibrahim Jun 20 '19 at 07:45
  • 1
    Helped only `webElement.sendKeys(Keys.BACK_SPACE); //do repeatedly, e.g. in while loop` in my strange case – Chaki_Black Sep 27 '19 at 16:20
  • 6
    `from selenium.webdriver.common.keys import Keys` just to make things easier for newcomers. – Burak Kaymakci Sep 09 '20 at 15:27
  • Sending `Keys.CONTROL + 'a'` worked for me until now, looks like something has changed either in Chrome or in Selenium so now it only sends 'a' char into my text_field which is not desired. Switched to `element.clear()` and it works perfectly with one line of code instead of 2 now, thank you! – rodikno Feb 24 '21 at 14:09
33

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)
tread
  • 10,133
  • 17
  • 95
  • 170
Jortega
  • 3,616
  • 1
  • 18
  • 21
  • What is the `;` for again? – tread Apr 03 '20 at 15:23
  • 1
    @surfer190 `;` is not necessary in python. I added it by accident. Good catch. – Jortega Apr 03 '20 at 22:53
  • `driver.find_element_by_id('foo').send_keys(...)` is [the same solution like](https://stackoverflow.com/a/27799120/3548833) `webElement.send_keys(...)` That `driver.find_element_by_id()` is one way how to return WebElement. You can use another way to locate an element. – Fenix Dec 30 '20 at 17:50
20

In the most recent Selenium version, use:

driver.find_element_by_id('foo').clear()
Union find
  • 7,759
  • 13
  • 60
  • 111
14

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

m0h17
  • 357
  • 3
  • 9
9

Am using selenium==3.141.0 and I don't know why

WebElement.clear()

is not working.

I used

WebElement.send_keys(Keys.CONTROL, 'a')
WebElement.send_keys(Keys.DELETE)

Which perfectly worked for me.

gitaoh
  • 191
  • 2
  • 4
8

The CTRL+A send_keys solution did not work for me in react. Testing in the browser directly, CTRL+A just sends the cursor to the start of the text element. Instead, this seems to be reliable for selecting all content in the element.

preferred_name_field.send_keys(Keys.SHIFT, Keys.ARROW_UP)
preferred_name_field.send_keys(Keys.DELETE)
Kevin Campbell
  • 629
  • 7
  • 5
6

It is general syntax

driver.find_element_by_id('Locator value').clear();
driver.find_element_by_name('Locator value').clear();
iamsankalp89
  • 4,607
  • 2
  • 15
  • 36
6

for java

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

or

webElement.clear();

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

vaibhavcool20
  • 861
  • 3
  • 11
  • 28
4

I recommend:

WebElement.send_keys([Keys.BACKSPACE] * 1000)

This is much faster and more elegant than a while loop. And Keys.BACKSPACE works on Mac. These all didn't work for me on Chrome on Mac:

WebElement.clear()
WebElement.send_keys(Keys.CONTROL, 'a')
WebElement.send_keys(Keys.DELETE)
while _ in range(1000):
    WebElement.send_keys(Keys.DELETE)
UFO
  • 131
  • 1
  • 4
3

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!

ShadowGames
  • 1,110
  • 1
  • 10
  • 15
2

Try:

driver=self.driver
driver.find_element_by_xpath('Path').send_keys(Keys.CONTROL + "a")      
driver.find_element_by_xpath('Path').send_keys(Keys.BACK_SPACE)
Ersel Er
  • 731
  • 6
  • 22
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 15 '22 at 06:25
1

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)
Victoria
  • 247
  • 4
  • 8
1

from selenium.webdriver.common.keys import Keys

element = driver.find_element_by_css_selector('foo') element.send_keys(Keys.CONTROL + Keys.BACKSPACE)

1

If clear() is not working, you can simulate the press of Backspace multiple times using: driver.get_element_by_id('foo').send_keys(Keys.BACKSPACE)

To execute this multiple times, use:

from selenium.webdriver.common.keys import Keys

# Replace 100 with the number of time you want to press backspace.
for i in range(0, 100): 
    driver.get_element_by_id('foo').send_keys(Keys.BACKSPACE)
Bagghi Daku
  • 652
  • 10
  • 15
1

First find the element

element = driver.find_element_by_id('your element id')

Clear text in Input or Textarea: If the element is input or textarea, you can directly remove the using clear() function.

element.clear()

Reset Radio button or Checkbox: Just click again the radio button or checkbox item.

element.click()

Deselect the Dropdow: In select, you can deselect using following ways.

Select select = new Select(element);

select.deselectByVisibleText("Female");
select.deselectByValue("1");
select.deselectByIndex(1);
select.deselectAll();
Samiya Khan
  • 241
  • 3
  • 4
1

Try using this

text=((Keys.BACKSPACE*20)+(Keys.DELETE * 20))
Shawn
  • 4,064
  • 2
  • 11
  • 23