Reputation: 4636
How can I simulate the RETURN keyboard press?
I have created a program which opens the print window in Firefox (through using the shortcut crtl+p). I now need to press RETURN to send this webpage to the printer.
Failed attempts:
1.
from selenium.webdriver.common.keys import Keys
element=browser.find_element_by_xpath("//body")
element.send_keys(Keys.RETURN)
2.
from selenium.webdriver import ActionChains
act = ActionChains(browser)
act.key_down(Keys.RETURN)
act.key_up(Keys.RETURN)
Both likely fail because their scope lies within the web browser whereas the print window pop up box lies in a scope outside the web browser.
Code:
import time
from selenium import webdriver
# Initialise the webdriver
browser = webdriver.Firefox()
time.sleep(3)
# Login to webpage
browser.get('www.google.com')
element=browser.find_element_by_xpath("//body")
element.send_keys(Keys.CONTROL, 'p')
Upvotes: 0
Views: 1058
Reputation: 4636
import ctypes
SendInput = ctypes.windll.user32.SendInput
# C struct redefinitions
PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure):
_fields_ = [("wVk", ctypes.c_ushort),
("wScan", ctypes.c_ushort),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", PUL)]
class HardwareInput(ctypes.Structure):
_fields_ = [("uMsg", ctypes.c_ulong),
("wParamL", ctypes.c_short),
("wParamH", ctypes.c_ushort)]
class MouseInput(ctypes.Structure):
_fields_ = [("dx", ctypes.c_long),
("dy", ctypes.c_long),
("mouseData", ctypes.c_ulong),
("dwFlags", ctypes.c_ulong),
("time",ctypes.c_ulong),
("dwExtraInfo", PUL)]
class Input_I(ctypes.Union):
_fields_ = [("ki", KeyBdInput),
("mi", MouseInput),
("hi", HardwareInput)]
class Input(ctypes.Structure):
_fields_ = [("type", ctypes.c_ulong),
("ii", Input_I)]
# Actuals Functions
def PressKey(hexKeyCode):
print('a')
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput( hexKeyCode, 0x48, 0, 0, ctypes.pointer(extra) )
x = Input( ctypes.c_ulong(1), ii_ )
SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def ReleaseKey(hexKeyCode):
print('b')
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput( hexKeyCode, 0x48, 0x0002, 0, ctypes.pointer(extra) )
x = Input( ctypes.c_ulong(1), ii_ )
SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def PressEnter():
time.sleep(2)
print('Running: Press Enter')
PressKey(0x0D) # 0x0D = Enter
time.sleep(0.2)
ReleaseKey(0x0D)
Upvotes: 2