8

I know how to send keys into a blank field as follows:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()
url = 'https://www.aircanada.com/en/'
browser.get(url)
browser.find_element_by_id('departure1').send_keys('28/03/2014')

However, since the field already has default value 'DD/MM/YYYY', how can I replace that field value with my value (i.e., '28/03/2014')

10
  • What is the real URL? (it's not example.com). Commented Mar 20, 2014 at 9:28
  • @barak manos please have a look at my edited question Commented Mar 20, 2014 at 9:40
  • are you referring to Departure Date field? Commented Mar 20, 2014 at 9:44
  • 2
    have you tried browser.find_element_by_id('departure1').clear();? Commented Mar 20, 2014 at 9:46
  • @barakmanos Did YOU see real website? Commented Mar 20, 2014 at 9:46

3 Answers 3

7

The clear() function is for this purpose.

from selenium import webdriver

browser = webdriver.Firefox()
url = 'https://www.aircanada.com/en/'
browser.get(url)

dep_date = browser.find_element_by_id('departure1')
dep_date.clear()
dep_date.send_keys('28/03/2014')

Haven't tested but this should do what you wanted, in a more 'Pythonic' way.

Sign up to request clarification or add additional context in comments.

1 Comment

Either this is broken or I'm misusing it. When I run clear() on a element it returns None and I can't send it new keys with send_keys()
6

Tested working for me:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()
url = 'https://www.aircanada.com/en/'
browser.get(url)

input_field = browser.find_element_by_id('departure1')

browser.execute_script("arguments[0].value = ''", input_field)
input_field.send_keys('12/04/2014')
input_field.send_keys(Keys.RETURN)

6 Comments

thanks upvoted but realizing which one to be accepted either yours or of barak manos
At times like these, you wish you had multiple answer accept feature?!;)
@Amith yes, i agree with you.
@neha - well both are good,so i had to delete mine. Why don't you try flipping a coin?:)
@Amith I really flipped a coin honestly once, and user1177636 won!
|
3

A couple of errors in your code:

  • The date format is wrong (should be DD/MM/YYYY, and not YYYY-MM-DD).
  • You need to delete the DD/MM/YYYY using 10 clicks on the backspace key.

Here is the fix:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()
url = 'https://www.aircanada.com/en/'
browser.get(url)
departure1 = browser.find_element_by_id('departure1')
departure1.send_keys(Keys.BACKSPACE*10)
departure1.send_keys('21/03/2014')
departure2 = browser.find_element_by_id('departure2')
departure2.send_keys(Keys.BACKSPACE*10)
departure2.send_keys('22/03/2014')

1 Comment

@Amith: Thanks, I tested it, and it does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.