python pyautogui+pynput鼠标键盘自动控制与监听

PyAutoGUI

参考https://blog.csdn.net/hfy1237/article/details/127960423

官方文档 https://pyautogui.readthedocs.io/en/latest/

1、基本函数
常用函数列表
函数名功能
基本pyautogui.size()返回包含分辨率的元组
pyautogui.PAUSE每个函数的停顿时间,默认0.1s
pyautogui.FAILSAFE是否开启防故障功能,默认True
键盘pyautogui.press(‘键盘字符’)按下并松开指定按键
pyautogui.keyDown(‘键盘字符’)按下指定按键
pyautogui.keyUp(‘键盘字符’)松开指定按键
pyautogui.hotkey(‘键盘字符1’, ‘键盘字符2’)按下多个指定键
鼠标pyautogui.position()返回当前鼠标当前位置的元组
pyautogui.moveTo(x,y,duration=1)   按绝对位置移动鼠标并设置移动时间
pyautogui.moveRel(x_rel,y_rel,duration=4)  按相对位置移动鼠标并设置移动时间
pyautogui.dragTo(x, y, duration=1)   按绝对位置拖动鼠标并设置移动时间
pyautogui.dragRel(x_rel, y_rel, duration=4)  按相对位置拖动鼠标并设置移动时间
pyautogui.click(x, y) 鼠标点击指定位置,默认左键
pyautogui.click(x, y, button=’left’)鼠标单击左键
pyautogui.click(x, y, button=’right’)鼠标单击右键
pyautogui.click(x, y, button=’middle’)  鼠标单击中间,即滚轮
pyautogui.doubleClick(10,10) 鼠标左键双击指定位置
pyautogui.rightClick(10,10)鼠标右键双击指定位置
pyautogui.middleClick(10,10) 鼠标中键双击指定位置
pyautogui.scroll(10) 鼠标滚轮向上滚动10个单位
2、press(), keyDowm(),keyUp(),hotKey()支持的有效字符串列表如下:
类别
字母‘a’, ‘b’, ‘c’, ‘d’, ‘e’,’f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’
数字‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’
符号‘\t’, ‘\n’, ‘\r’, ‘ ‘, ‘!’, ‘”‘, ‘#’, ‘$’, ‘%’, ‘&’, “‘”, ‘(‘, ‘)’, ‘*’, ‘+’, ‘,’, ‘-‘, ‘.’, ‘/’, , ‘:’, ‘;’, ‘<‘, ‘=’, ‘>’, ‘?’, ‘@’, ‘[‘, ‘\\’, ‘]’, ‘^’, ‘_’, ‘`’, ‘{‘, ‘|’, ‘}’, ‘~’,
F键‘f1’, ‘f10’, ‘f11’, ‘f12’, ‘f13’, ‘f14’, ‘f15’, ‘f16’, ‘f17’, ‘f18’, ‘f19’, ‘f2’, ‘f20’, ‘f21’, ‘f22’, ‘f23’, ‘f24’, ‘f3’, ‘f4’, ‘f5’, ‘f6’, ‘f7’, ‘f8’, ‘f9’,
数字键盘‘num0’, ‘num1’, ‘num2’, ‘num3’, ‘num4’, ‘num5’, ‘num6’, ‘num7’, ‘num8’, ‘num9’, 
其他‘accept’, ‘add’, ‘alt’, ‘altleft’, ‘altright’, ‘apps’, ‘backspace’, ‘browserback’, ‘browserfavorites’, ‘browserforward’, ‘browserhome’, ‘browserrefresh’, ‘browsersearch’, ‘browserstop’, ‘capslock’, ‘clear’, ‘convert’, ‘ctrl’, ‘ctrlleft’, ‘ctrlright’, ‘decimal’, ‘del’, ‘delete’, ‘divide’, ‘down’, ‘end’, ‘enter’, ‘esc’, ‘escape’, ‘execute’, ‘final’, ‘fn’, ‘hanguel’, ‘hangul’, ‘hanja’, ‘help’, ‘home’, ‘insert’, ‘junja’, ‘kana’, ‘kanji’, ‘launchapp1’, ‘launchapp2’, ‘launchmail’, ‘launchmediaselect’, ‘left’, ‘modechange’, ‘multiply’, ‘nexttrack’, ‘nonconvert’, , ‘numlock’, ‘pagedown’, ‘pageup’, ‘pause’, ‘pgdn’, ‘pgup’, ‘playpause’, ‘prevtrack’, ‘print’, ‘printscreen’, ‘prntscrn’, ‘prtsc’, ‘prtscr’, ‘return’, ‘right’, ‘scrolllock’, ‘select’, ‘separator’, ‘shift’, ‘shiftleft’, ‘shiftright’, ‘sleep’, ‘space’, ‘stop’, ‘subtract’, ‘tab’, ‘up’, ‘volumedown’, ‘volumemute’, ‘volumeup’, ‘win’, ‘winleft’, ‘winright’, ‘yen’, ‘command’, ‘option’, ‘optionleft’, ‘optionright’

一般功能

pyautogui.position() # 鼠标当前坐标

pyautogui.size() # 获取屏幕尺寸 

pyautogui.onScreen(x, y) #判断指定坐标 (x,y) 是否在屏幕内

故障保险

pyautogui.PAUSE = 2.5 # 控制调用 PyAutoGUI 后的暂停时间(单位:秒)

pyautogui.FAILSAFE = True # 鼠标移动到左上角将引发一个 `pyautogui.FailSafeException `从而中断程序

鼠标控制

pyautogui.moveTo(x, y, duration=num_seconds) # 在 num_Second 秒内将鼠标**移动**到指定坐标

pyautogui.moveRel(xOffset, yOffset, duration=num_seconds)  #  相对于鼠标当前位置移动鼠标

pyautogui.dragTo(x, y, duration=num_seconds) # 在 num_Second 秒内将鼠标拖动到指定坐标

pyautogui.dragRel(xOffset, yOffset, duration=num_seconds) # 相对于鼠标当前位置拖动鼠标

pyautogui.click(x=moveToX, y=moveToY, clicks=num_of_clicks, interval=secs_between_clicks,button = 'left') #调用click()只会让鼠标在当前位置用左键单击一次,但关键字参数可以改变这一点,button关键字参数可以left是middle或right。

#单独调用指定键的点击事件
pyautogui.rightClick(x=moveToX, y=moveToY)
pyautogui.middleClick(x=moveToX, y=moveToY)
pyautogui.doubleClick(x=moveToX, y=moveToY)
pyautogui.tripleClick(x=moveToX, y=moveToY)

#正数控制滚轮将向上滚动,负数控制滚轮将向下滚动
pyautogui.scroll(amount_to_scroll, x=moveToX, y=moveToY)
pyautogui.vscroll(amount_to_scroll) # 垂直滚动鼠标
pyautogui.hscroll(amount_to_scroll)  # 水平滚动鼠标
#单独调用鼠标的按下和松开事件 
pyautogui.mouseDown(x=moveToX, y=moveToY, button='left')
pyautogui.mouseUp(x=moveToX, y=moveToY, button='left')

键盘控制

pyautogui.typewrite('Hello world!\n', interval=secs_between_keys) # 在键盘光标处输入指定文本

 pyautogui.typewrite(['a', 'b', 'c', 'left', 'backspace', 'enter', 'f1'], interval=secs_between_keys) # 传递密钥等

#键盘热键(如Ctrl-S或Ctrl-Shift-1)可以通过将键名称列表传递给hotkey()来完成:
pyautogui.hotkey('ctrl', 'c')  # ctrl-c 复制
pyautogui.hotkey('ctrl', 'v')  # ctrl-v 粘贴

# 单独调用按钮的点击事件和松开事件:
pyautogui.keyDown('键名称')
pyautogui.keyUp('键名称') 

消息框函数

pyautogui.alert('这将显示带有确定按钮的文本。')
pyautogui.confirm('这将显示带有确定和取消按钮的文本。')
pyautogui.prompt('这样用户就可以输入一个字符串,然后按确定。')
# 显示一个简单的消息框,其中包含文本和一个确定按钮。返回单击的按钮的文本
pyautogui.alert(text='', title='', button='OK')
# 显示带有确定和取消按钮的消息框。可以自定义按钮的数量和文本。返回单击的按钮的文本
pyautogui.confirm(text='', title='', buttons=['OK', 'Cancel'])
# 显示带有文本输入和确定和取消按钮的消息框。返回输入的文本,如果单击了取消,则返回None。
pyautogui.prompt(text='', title='' , default='')
# 显示带有文本输入和确定和取消按钮的消息框。键入的字符显示为*。返回输入的文本,如果单击了取消,则返回None。
pyautogui.password(text='', title='', default='', mask='*')

截图功能

pyautogui.screenshot()  # 返回Pillow/PIL图像对象
pyautogui.screenshot('foo.png')  # 返回Pillow/PIL图像对象,并将其保存到文件
pyautogui.screenshot(region=(0,0, 300, 400))  # 捕获指定范围
pyautogui.locateOnScreen('looksLikeThis.png') #返回在当前界面找到第一个图标位置的元组 (left, top, width, height) 

LocateAllOnScreen()# 函数将返回屏幕上找到的所有位置的生成器

for i in pyautogui.locateAllOnScreen('looksLikeThis.png')

#返回屏幕上图像所在位置的XY坐标。

pyautogui.locateCenterOnScreen('looksLikeThis.png')  # 返回中心坐标 (898,423)

示例

案例获取鼠标的位置,方便复制我们定位的鼠标坐标点到代码中

import pyautogui
import time

获取鼠标位置

def get_mouse_positon():
  time.sleep(5) # 准备时间
  print('开始获取鼠标位置')
  try:
    for i in range(10):
      # Get and print the mouse coordinates.
      x, y = pyautogui.position()
      positionStr = '鼠标坐标点(X,Y)为:{},{}'.format(str(x).rjust(4), str(y).rjust(4))
      pix = pyautogui.screenshot().getpixel((x, y)) # 获取鼠标所在屏幕点的RGB颜色
      positionStr += ' RGB:(' + str(pix[0]).rjust(3) + ',' + str(pix[1]).rjust(3) + ',' + str(pix[2]).rjust(
        3) + ')'
      print(positionStr)
      time.sleep(0.5) # 停顿时间
  except:
    print('获取鼠标位置失败')

if __name__ == "__main__":
  get_mouse_positon()

pynput 监听

参考 https://blog.csdn.net/lidashent/article/details/121892655

监听按键

import pynput.keyboard as pk
def on_press(key):
    # 监听按键
    key=str(key)[1]
    print("按键为",key)

#连接事件以及释放

with pk.Listener(on_press=on_press) as pklistener:
    pklistener.join()

侦听鼠标

import pynput.mouse as pm
import threading
def on_click(x, y, button, pressed):
    # 监听鼠标点击
    if pressed:
        print("按下坐标")
        mxy="{},{}".format(x, y)
        print(mxy)
        print(button)
    if not pressed:
        # Stop listener
        return False
def ls_k_thread():
    while(1):
        with pm.Listener(on_click=on_click) as pmlistener:
            pmlistener.join()
def analyse_pic_thread():
    r = threading.Thread(target=ls_k_thread)
    r.start()
analyse_pic_thread()

安装pynput模块

pip install pynput
#使用ctrl+v 快捷粘贴时候用到
pip install pyperclip

键盘控制

from pynput.keyboard import Key, Controller as c_keyboard
from pynput.mouse import Button, Controller as c_mouse

keyboard = c_keyboard()
#字符与数字
keyboard.press('a')
keyboard.release('a')

keyboard.press('A')
keyboard.release('A')

keyboard.press('1')
keyboard.release('1')
#非数字与字母键 详情: https://pynput.readthedocs.io/en/latest/keyboard.html#pynput.keyboard.Key
keyboard.press(Key.enter);
keyboard.release(Key.enter);
#组合
##全选
keyboard.press(Key.ctrl)
keyboard.press('a')
time.sleep(2)
keyboard.release('a')
keyboard.release(Key.ctrl)
###或者
with keyboard .pressed(Key.ctrl):
 keyboard.press('a')
 keyboard.release('a')
##复制
seller_nick = 'www.baidu.com/a.php?a=a&b=2'
pyperclip.copy('https://'+seller_nick.replace('amp;',''))
##粘贴
keyboard.press(Key.ctrl)
keyboard.press('v')
time.sleep(1)
keyboard.release('v')
keyboard.release(Key.ctrl)
##回车
keyboard.press(Key.enter);
keyboard.release(Key.enter);

鼠标控制

from pynput.keyboard import Key, Controller as c_keyboard
from pynput.mouse import Button, Controller as c_mouse

mouse= c_mouse()
#点击
mouse.click(Button.left, 2)
#双击
mouse.click(Button.left, 2)
##按下右键
mouse.press(Button.right)
##释放右键
mouse.release(Button.right)
#鼠标坐标
print(mouse.position) 
##x轴坐标
print(mouse.position[0]) 
##y轴坐标
print(mouse.position[1])
#移动
##移动到绝对坐标
mouse.position = (400, 38)
##相对当前坐标移动
mouse.move(300, 2)
#滑动
mouse.press(Button.left)
mouse.move(300, 2)
mouse.release(Button.left)

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年11月14日
下一篇 2023年11月14日

相关推荐