python: How can I press arrow keys randomly selenium

14,200

This seem to work. Try it and let me know the result:

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

moves = [Keys.LEFT, Keys.DOWN, Keys.RIGHT, Keys.UP]
while True:
    driver.find_element_by_css_selector('body').send_keys(random.choice(moves))
Share:
14,200
Freddy
Author by

Freddy

Maker

Updated on June 05, 2022

Comments

  • Freddy
    Freddy almost 2 years

    I am trying to make a program which plays 2048 by randomly choosing arrow keys.

    I tried something like this:

     moves = [htmlElem.send_keys(Keys.UP),htmlElem.send_keys(Keys.RIGHT),htmlElem.send_keys(Keys.DOWN),htmlElem.send_keys(Keys.LEFT)]
    
    
    while True:
        random.choice(moves)
    

    This is not working. I tried print(random.choice(moves)), but it infinite loop of None

    So how can I press arrows keys randomly using Selenium?

  • Freddy
    Freddy about 7 years
    It works I changes moves = [Keys.LEFT, Keys.DOWN, Keys.RIGHT, Keys.UP] and htmlElem.send_keys(random.choice(moves))