Home > front end >  Selenium send_keys alternative?
Selenium send_keys alternative?

Time:01-02

Hello fellow programmers, I'm using selenium to submit a form. On all of the inputs send_keys is working perfectly. But there's an otp verification Input if i use send_keys it triggers a function to send another otp code via email and the page starts loading again ... Can't find any function callback on the div but that's the way it works, if i type it from my keyboard it works. Solutions i implemented :

1 - I made this function to work around it but it didn't help.

def keyTrans(cod):
    str = ''
    for c in cod:
        str = str   'keys.Keys.NUMPAD{}/'.format(c)
    L=str.split('/')
    print(L)
    return L

2 - I used pynput lib

    wait.until(EC.element_to_be_clickable(otp)).click()
    keyboard = Controller()
    keyboard.type(str(code))

Both solutions ended up in causing the browser to load and send another otp ... Any of you have seen something like this before ? or do you suggest anything else to try ? Also as i mentioned i didn't find the fn callback on this otp input so i can't be 100% sure that keyboard is causing it but most likely it is since whenever i type it from my keyboard it works just fine .

That's the HTML the otp input is causing the problem

CodePudding user response:

Try sending the text using the ActionChains.
You will need to import

from selenium.webdriver.common.action_chains import ActionChains

Initialize the actions object with

actions = ActionChains(driver)

Get the web element, let's call it "input"

input = driver.find_element_by_xpath("//input[@name='otp']")

and then perform click and "send_keys" with the

actions.move_to_element(input).click().send_keys(your_text).perform()

CodePudding user response:

This worked driver.execute_script('arguments[0].value=arguments[1];', op, code) Thanks to https://stackoverflow.com/users/9901261/arundeep-chohan comment, with op being the otp element and code obviously the extracted otp code.

Worth to mention i tried different other ways of implementing the script and all failed . driver.execute_script(f'document.getElementById("otp").value = "{code}";') driver.execute_script('document.getElementById("otp").innerHTML = "{}";'.format(code)) and other variations that i deleted

  • Related