码迷,mamicode.com
首页 > 编程语言 > 详细

python 模拟windows键盘按键的封装

时间:2018-07-22 20:48:23      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:==   drive   finish   with   NPU   inpu   sleep   按键   encoding   

 

代码:在执行的时候,把光标放在指定的地方,在此例中,点击运行后把光标放到结果区域,粘贴的时候是粘贴到光标所在的问题,如过是运行脚本在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键盘按键的封装

标签:==   drive   finish   with   NPU   inpu   sleep   按键   encoding   

原文地址:https://www.cnblogs.com/xiaxiaoxu/p/9351229.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!