The Python Oracle

Clear text from textarea with selenium

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping

--

Chapters
00:00 Question
00:34 Accepted answer (Score 288)
00:44 Answer 2 (Score 138)
01:49 Answer 3 (Score 32)
02:11 Answer 4 (Score 19)
02:26 Thank you

--

Full question
https://stackoverflow.com/questions/7732...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #selenium #seleniumwebdriver

#avk47



ACCEPTED ANSWER

Score 303


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



ANSWER 2

Score 147


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.




ANSWER 3

Score 32


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)



ANSWER 4

Score 20


In the most recent Selenium version, use:

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