Search code examples
pythonseleniumsendkeys

How can I use send_keys at random intervals with Python Selenium?


For example, when writing "Hello", I would like to wait for a random amount of time between 0.03 and 0.2 seconds for each character to be typed.

Is it possible to accomplish this using a send_keys function with a random wait time between 0.03 and 0.2 seconds for each character?

Here is the code I am using:

import random
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
driver = webdriver.Chrome(executable_path='C:/Users/X/chromedriver.exe',chrome_options=chrome_options)

driver.get ('https://example.com/login')

driver.find_element_by_name("session[username_or_email]").send_keys('H')
time.sleep(random.uniform(0.03,0.2))

driver.find_element_by_name("session[username_or_email]").send_keys('e')
time.sleep(random.uniform(0.03,0.2))

driver.find_element_by_name("session[username_or_email]").send_keys('l')
time.sleep(random.uniform(0.03,0.2))

driver.find_element_by_name("session[username_or_email]").send_keys('l')
time.sleep(random.uniform(0.03,0.2))

driver.find_element_by_name("session[username_or_email]").send_keys('o')
time.sleep(random.uniform(0.03,0.2))

Solution

  • You almost have it. Making a function that breaks your string into characters, and sends them one at a time will accomplish this without hard-coding anything:

    def send_keys_delayed(elementName, str)
       for char in str:
          driver.find_element_by_name(elementName).send_keys(char)
          time.sleep(random.uniform(0.03,0.2))