Duplicate of https://mcmap.net/q/1164659/-how-to-send-keys-to-an-element-with-type-number-using-selenium-python
In my case, I'm working on chromedriver. I have a form with an input type = number
. When attempting to send_keys, nothing happens.
I tried driver.execute_script(f"arguments[0].value = '{text}';", element)
.
This solution writes the number BUT the form does not recognize it.
It's exactly the same as :
script = f"""document.evaluate({xpath}, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.value = '{text}';"""
driver.execute_script(script)
I also tried an alternative pyautogui.typewrite(text)
but it produces the same result as the previous solution.
So I need to perform a real keyboard touch instead of the simulated one by selenium.
I'm sorry to say that it is mandatory to install 2 libraries :
pynput
(which requires evdev
)
Initially, the pip install did not work, so I had to execute the following commands:
sudo apt-get install build-essential
pip install evdev
pip install pynput
OLD SOLUTION TLDR:
from pynput.keyboard import Key, Controller
text = "my text"
xpath = "//my//xpath"
self.wait.until(EC.element_to_be_clickable((By.XPATH, xpath))).click()
keyboard = Controller()
for char in text:
keyboard.press(char)
keyboard.release(char)
This solution doesn't works in an endless mode.
EDIT BETTER SOLUTION
Selenium is capable of interacting with keys.
def inputNumberWithKeyboard(self, element, number):
for digit in number:
self.actions.click(element).send_keys(eval(f"Keys.NUMPAD{digit}")).perform()
# if digit is 1 the command will be
# self.actions.click(element).send_keys(eval(Keys.NUMPAD1).perform()
send_keys
in a loop:for x in '12': field.send_keys(x)
? – Vassalfield.click()
does focus on the input field.field.send_keys
also focus on the field but nothing more. – Traveled