如何模拟RETURN键盘按下?
我创建了一个在Firefox中打开打印窗口的程序(通过使用快捷键crtl + p)。我现在需要按RETURN将此网页发送到打印机。
尝试失败:
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)
两者都可能失败,因为它们的范围位于Web浏览器中,而打印窗口弹出框位于Web浏览器之外的范围内。
代码:
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')
答案 0 :(得分:2)
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)