Search code examples
pythonseleniumheadless

Python send_keys method is not sending the desired values


I am writing a script that will fill out a form. It sends a string with a certain value to the text field where the value should be entered. However, while the text field always becomes entered, the characters sometimes become scrambled. For instance, in one field, the value to be entered was:

420420420420420

Yet, the screenshot from the filled out field yielded this value:

420404204204202

Why is this? Is there an alternative method that can be used to avoid this issue?

Specifically, these lines of code cause the most issues:

client.find_element_by_id("nnaerb").send_keys(checkout_parameters[9])
client.find_element_by_id("credit_card_month").send_keys(checkout_parameters[10])
client.find_element_by_id("credit_card_year").send_keys(checkout_parameters[11]) 

Solution

  • Hmm that's weird that it would send them in the incorrect order. You could try something like this maybe:

    for key in checkout_parameters[9]:
        client.find_element_by_id("nnaerb").send_keys(key)
    

    This way you specify them to be sent one at a time in order?

    Or you could really break it down and use ActionChains:

    from selenium.webdriver import ActionChains
    action_chains = ActionChains(client)
    action_chains.move_to_element(client.find_element_by_id("nnaerb"))
    action_chains.click()
    for key in checkout_parameters[9]:
        action_chains.key_down(key)
        action_chains.key_up(key)
    action_chains.perform()
    

    edit

    From selenium documentation it says with regard to .key_down():

    Should only be used with modifier keys (Control, Alt and Shift).

    So it looks like using ActionChains would be like:

    from selenium.webdriver import ActionChains
    action_chains = ActionChains(client)
    action_chains.move_to_element(client.find_element_by_id("nnaerb"))
    action_chains.click()
    for key in checkout_parameters[9]:
        action_chains.send_keys(key)
    action_chains.perform()
    

    Which doesn't look like it would yield better results here than my first code block.