python 模擬windows鍵盤按鍵的封裝
代碼:在執行的時候,把光標放在指定的地方,在此例中,點擊運行後把光標放到結果區域,粘貼的時候是粘貼到光標所在的問題,如過是運行腳本在web元素輸入框中輸入的話,不能移動光標到其他位置
#encoding=utf-8
import win32api
import win32con
class KeyboardKeys(object):
#模擬鍵盤按鍵類
VK_CODE={
‘enter‘:0x0D,
‘ctrl‘:0x11,
‘v‘:0x56}
@staticmethod
def keyDown(keyName):
#按下按鍵
win32api.keybd_event(KeyboardKeys.VK_CODE[keyName],0,0,0)
@staticmethod
def keyUp(keyName):
#釋放按鍵
win32api.keybd_event(KeyboardKeys.VK_CODE[keyName],0,win32con.KEYEVENTF_KEYUP,0)
@staticmethod
def oneKey(key):#對前兩個方法的調用
#模擬單個按鍵
KeyboardKeys.keyDown(key)
KeyboardKeys.keyUp(key)
@staticmethod
def twoKeys(key1,key2):#對前面函數的調用
#模擬兩個組合鍵
KeyboardKeys.keyDown(key1)
KeyboardKeys.keyDown(key2)
KeyboardKeys.keyUp(key2)
KeyboardKeys.keyUp(key1)
if __name__==‘__main__‘:
from util.clipboard import *
from selenium import webdriver
import time
Clipboard.setText(u"hello world")
time.sleep(3)
# driver=webdriver.Firefox(executable_path=r‘c:\\geckodriver‘)
# driver.get(‘http://www.baidu.com‘)
# driver.find_element_by_xpath("//input[@id=‘kw‘]").click()
# KeyboardKeys.twoKeys("ctrl","v")
KeyboardKeys.twoKeys(‘ctrl‘,‘v‘)
結果:ok
C:\Python27\python.exe D:/test/hybrid_version2/util/keyboard.py
hello world
Process finished with exit code 0
python 模擬windows鍵盤按鍵的封裝