Python-模拟鼠标键盘动作

作者: 屋顶之树 | 来源:发表于2016-01-16 15:22 被阅读21881次

    在使用电脑的时候,偶尔有需求要模拟鼠标键盘,进行一些机械重复的操作(刷新网页、抢票、某些小游戏等)。如果为此专门下载一个按键精灵,总感觉杀鸡用牛刀,所以就开始探索一些轻量级解决方案。本人电脑上配置了Python,自然就想到那句名言

    人生苦短,我用Python
    Life is short, you need Python -Bruce Eckel

    方案

    参考网上的各种例子后,发现了PyUserInput这个项目。在配置完成后,调用非常简便。

    • 准备

    进入项目主页,可以看到这个Python库是跨平台支持的,但是对应不同平台,需要安装依赖库。

    Linux - Xlib (python-xlib)
    Mac - Quartz, AppKit
    Windows - pywin32, pyHook


    • 安装

    使用pip工具,直接安装

    pip install PyUserInput


    • 调用方法

    以下部分参考PyUserInput项目在Python官网的说明只做简要翻译,方便理解。详细方法可以调用help()函数查看。

    在安装完PyUserInput后,pymousepykeyboard模块就被安装到你的Python路径下。

    建立一个鼠标和键盘对象:

    from pymouse import PyMouse
    from pykeyboard import PyKeyboard
    m = PyMouse()
    k = PyKeyboard()
    

    接下来是一个示例,完成点击屏幕中央并键入“Hello, World!”的功能:

    x_dim, y_dim = m.screen_size()
    m.click(x_dim/2, y_dim/2, 1)
    k.type_string('Hello, World!')
    

    PyKeyboard还有很多种方式来发送键盘键入:

    # pressing a key
    k.press_key('H')
    # which you then follow with a release of the key
    k.release_key('H')
    # or you can 'tap' a key which does both
    k.tap_key('e')
    # note that that tap_key does support a way of     repeating keystrokes with a interval time between each
    k.tap_key('l',n=2,interval=5) 
    # and you can send a string if needed too
    k.type_string('o World!')
    

    并且它还支持很多特殊按键:

    #Create an Alt+Tab combo
    k.press_key(k.alt_key)
    k.tap_key(k.tab_key)
    k.release_key(k.alt_key)
    k.tap_key(k.function_keys[5]) # Tap F5
    k.tap_key(k.numpad_keys['Home']) # Tap 'Home' on the numpad
    k.tap_key(k.numpad_keys[5], n=3) # Tap 5 on the numpad, thrice
    

    注意,你也可以使用press_keys方法将多个键一起发送(例如,使用某些组合键):

    # Mac example
    k.press_keys(['Command','shift','3'])
    # Windows example
    k.press_keys([k.windows_l_key,'d'])
    

    平台之间的一致性是一个很大的挑战,请参考你使用的操作系统对应的源码,来理解你需要使用的按键格式。例如:

    # Windows
    k.tap_key(k.alt_key)
    # Mac
    k.tap_key('Alternate')
    

    我还想特别说明一下PyMouseEventPyKeyboardEvent的使用。

    这些对象是一个架构用于监听鼠标和键盘的输入;他们除了监听之外不会做任何事,除非你继承他们【注1】。PyKeyboardEvent为编写完成,所以这里是一个继承PyMouseEvent的例子:

    from pymouse import PyMouseEvent
    
    def fibo():
        a = 0
        yield a 
        b = 1
        yield b 
        while True:
            a, b = b, a+b
            yield b 
    
    class Clickonacci(PyMouseEvent):
        def __init__(self):
            PyMouseEvent.__init__(self)
            self.fibo = fibo()
    
        def click(self, x, y, button, press):
            '''Print Fibonacci numbers when the left click is pressed.'''
            if button == 1:
                if press:
                    print self.fibo.next()
            else: # Exit if any other mouse button used
                self.stop()
    
    C = Clickonacci()
    C.run()
    

    注1:原文为

    These objects are a framework for listening for mouse and keyboard input; theydon't do anything besides listen until you subclass them.

    相关文章

      网友评论

      • 御史神风:似乎无论使用PyUserInput还是pyautogui都无法点击蓝叠模拟器
      • ibob2012:问一下ctrl组合键的写法,比如ctrl+a ctrl+c,我觉得这些很常用,但网上却未提及
        b830104eafe0:k = PyKeyboard() #模拟键盘输入
        m = PyMouse() # 模拟鼠标点击

        time.sleep(random.randint(3,6))
        k.press_key(k.alt_key)
        k.press_key(k.space)
        time.sleep(0.2)
        k.tap_key('x')
        k.release_key(k.space)
        k.release_key(k.alt_key)

        这是 alt + space + x 组合键的使用,其他组合键用法也是相同的
      • 姜北生:pip install PyUserInput 这个直接安装会将PyUserInput 项目里的依赖库一块安装了吗?
        b830104eafe0:装PyUserInput 应该是需要先装 PyHook 这个库,不然PyUserInput 应该装不上去
      • 31e62f2e1f9b:很有用,超级赞
      • 镏金糖豆:貌似现在用不了了,
        Could not find a version that satisfies the requirement pyHook (from PyUserInput) (from versions: )
        No matching distribution found for pyHook (from PyUserInput)
        pyhook这个库木有了。。
        79038c16e18b:需要先安装pywin32 (https://github.com/mhammond/pywin32/releases)
        然后安装pyhook (https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyhook)
      • 600802e9c3ab:不错 收下了 我的网站xyrland.com
      • NoTKS:有帮助,点个赞

      本文标题:Python-模拟鼠标键盘动作

      本文链接:https://www.haomeiwen.com/subject/dxwhkttx.html