Need to send key presses to a webpage(html5 game)

463 views Asked by At

Trying to build a bot for experimenting with A.I for a webpage. The webpage in question is a game(HTML5).

I want to send keys (up, down, left, right, space)to an externally opened webpage to control a bot in the game.

I looked into mechanize, but it feels to me that its constructed for forms and stuff.

BTW, i'm taking A.I. right now, hence the curiosity. Any help would be appreciated. Thank You.

1

There are 1 answers

0
TankorSmash On

Depending on how you want to approach this, and assuming you're on Windows, the guide here suggests that you just use The Python Imaging Library (for reading the screen), Numpy and PyWin (for actually clicking on the game). The equivalent packages for Win64 may be available here

To directly answer your question though:

import win32api, win32con

def leftClick():
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
    time.sleep(.1)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
    print "Click."          #completely optional. But nice for debugging purposes.

Selenium also offers something similiar to Mechanize in that you get control of a browser, although it has to be launched by Selenium itself, it can't just hook into a currently running process. You're able to send a click event directly to an HTML element, which might be just what you're looking for here.