Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear text from textarea with selenium

People also ask

What is clear method in Selenium?

Clear Method. Thrown when the target element is no longer valid in the document DOM. If this element is a text entry element, the Clear() method will clear the value. It has no effect on other elements.

What is the use of JavascriptExecutor in Selenium Webdriver?

What is JavascriptExecutor in Selenium? In simple words, JavascriptExecutor is an interface that is used to execute JavaScript with Selenium. To simplify the usage of JavascriptExecutor in Selenium, think of it as a medium that enables the WebDriver to interact with HTML elements within the browser.

How do I get text to type a textbox?

We can get the entered text from a textbox in Selenium webdriver. To obtain the value attribute of an element in the html document, we have to use the getAttribute() method. Then the value is passed as a parameter to the method. Let us consider a textbox where we entered some text and then want to get the entered text.


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

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.


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)

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