欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python使用pyautogui模块实现自动化鼠标和键盘操作示例

程序员文章站 2023-10-17 09:25:00
本文实例讲述了python使用pyautogui模块实现自动化鼠标和键盘操作。分享给大家供大家参考,具体如下: 一、pyautogui模块简要说明 ## 使用 py...

本文实例讲述了python使用pyautogui模块实现自动化鼠标和键盘操作。分享给大家供大家参考,具体如下:

一、pyautogui模块简要说明

## 使用 pyautogui 模块相关函数,可以模拟鼠标及键盘操作, 完整说明文档见: http://pyautogui.readthedocs.org/
# pip install pyautogui
# 要注意的是,模拟移动鼠标与击键可能太快,导致其他程序跟不上,并且程序可能失去控制,
# 需要掌握如何从问题中恢复,至少要能中止它。
# 防止或恢复gui自动化问题
# 1) 使用pyautogui.pause设置每个pyautogui函数调用在执行动作后暂停的秒数
# 2) pyautogui自动防故障功能:将鼠标移到屏幕的左上角,来抛出failsafeexception异常

二、控制鼠标移动与交互

三、屏幕快照与识别比较

四、控制键盘

五、综合例子

具体见以下代码及说明:

## 使用 pyautogui 模块相关函数,可以模拟鼠标及键盘操作, 完整说明文档见: http://pyautogui.readthedocs.org/
# pip install pyautogui
# 要注意的是,模拟移动鼠标与击键可能太快,导致其他程序跟不上,并且程序可能失去控制,
# 需要掌握如何从问题中恢复,至少要能中止它。
# 防止或恢复gui自动化问题
#  1) 使用pyautogui.pause设置每个pyautogui函数调用在执行动作后暂停的秒数
#  2) pyautogui自动防故障功能:将鼠标移到屏幕的左上角,来抛出failsafeexception异常
import pyautogui
pyautogui.pause = 1
pyautogui.failsafe = true      # 启用自动防故障功能
width,height = pyautogui.size()   # 屏幕的宽度和高度
pyautogui.position()        # 鼠标当前位置
## 控制鼠标移动
for i in range(10):
  pyautogui.moveto(100,100,duration=0.25)   # 移动到 (100,100)
  pyautogui.moveto(200,100,duration=0.25)
  pyautogui.moveto(200,200,duration=0.25)
  pyautogui.moveto(100,200,duration=0.25)
for i in range(10):
  pyautogui.moverel(100,0,duration=0.25)    # 从当前位置右移100像素
  pyautogui.moverel(0,100,duration=0.25)    # 向下
  pyautogui.moverel(-100,0,duration=0.25)   # 向左
  pyautogui.moverel(0,-100,duration=0.25)   # 向上
## 例子:持续获取鼠标位置并更新显示
# 1.获取当前坐标
# 2.在屏幕上打印,并删除之前打印的坐标
# 3.处理异常,并能按键退出
# displays the mouse cursor's currrent position.
import pyautogui
print('press ctrl-c to quit.')
try:
  while true:
    # get and print the mouse coordinates.
    x,y = pyautogui.position()
    positionstr = 'x: '+str(x).rjust(4)+' y:'+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,end='')           # end='' 替换了默认的换行
    print('\b'*len(positionstr),end='',flush=true) # 连续退格键并刷新,删除之前打印的坐标,就像直接更新坐标效果
except keyboardinterrupt:               # 处理 ctrl-c 按键
  print('\ndone.')
## 控制鼠标交互
# pyautogui.click() 封装了 pyautogui.mousedown()和pyautogui.mouseup(), 这两个函数也可以单独使用
# pyautogui.doubleclick() 双击左键, pyautogui.rightclick() 双击右键,pyautogui.middleclick() 双击中键
import pyautogui
pyautogui.click(10,5)           # 在(10,5)单击鼠标,默认左键
pyautogui.click(100,150,button='left')
pyautogui.click(200,250,button='right')
# pyautogui.dragto()  按键并拖动鼠标移动,参数为坐标,与moveto相同
# pyautogui.dragrel()  按键并拖动鼠标移动,参数为距离,与moverel相同
import pyautogui,time
time.sleep(5)
# 这里停顿5秒,用于手工打开windows绘图应用,并选中铅笔或画图工具,让鼠标停留在画图工具的窗口中
# 或使用在线paint (http://sumopaint.com)
pyautogui.click()   # click to put drawing program in focus
distance = 200
while distance > 0 :
  pyautogui.dragrel(distance,0,duration=0.2) # move right
  distance = distance - 5
  pyautogui.dragrel(0,distance,duration=0.2) # move down
  pyautogui.dragrel(-distance,0,duration=0.2) # move left
  distance = distance - 5
  pyautogui.dragrel(0,-distance,duration=0.2) # move up
print('done')
pyautogui.scroll(200)     # 鼠标向上滚动200像素
pyautogui.scroll(-100)    #   负数向下
import pyperclip
numbers = ''
for i in range(200):
  numbers = numbers + str(i) + '\n'
pyperclip.copy(numbers)
print(numbers)
# 这里手动打开一个文本窗口,粘贴
import time,pyautogui
time.sleep(5);pyautogui.scroll(100)
## 分析屏幕快照
import pyautogui
im = pyautogui.screenshot()   # 获取屏幕快照
im.getpixel((50,200))      # (130,135,144)
pyautogui.pixelmatchescolor(50,200,(130,135,144))  # true 可用来判断屏幕是否发生变化
pyautogui.pixelmatchescolor(50,200,(255,135,144))  # false
# 图像定位识别
pyautogui.locateonscreen('submit.png')  # 在屏幕上查找匹配与文件相同的区域--每个区域像素都要相同 左,顶,宽,高
pyautogui.center(pyautogui.locateonscreen('submit.png')) # 获取匹配图像中心点坐标
pyautogui.click((678,759))        # 点击该区域核心
list(pyautogui.locateallonscreen('submit.png'))  # 匹配到多处,返回区域list
## 控制键盘
pyautogui.click(100,100);pyautogui.typewrite('hello python')
pyautogui.typewrite(['a','b','left','left','x','y']) # typewrite可传入击键列表,这里输出xyab,left是左箭头
print(pyautogui.keyboard_keys)      # pyautogui接受的所有可能字符串
pyautogui.press('enter')         # 接受按键命令
pyautogui.keydown('shift');pyautogui.press('4');pyautogui.keyup('shift')  # 输出 $ 符号的按键
#热键组合
pyautogui.keydown('ctrl')
pyautogui.keydown('c')
pyautogui.keyup('c')
pyautogui.keyup('ctrl')
# 这四句是组合 ctrl-c,类似这种顺序按下,再反序释放的,可以用hotkey()
pyautogui.hotkey('ctrl','c')        # 同上面四句,组合键
pyautogui.hotkey('ctrl','alt','shift','s') # ctrl-alt-shift-s 热键组合
## 综合例子: 自动填表程序
# http://autbor.com/form
# 将电子表格中的大量数据自动输入到另一个应用的表单界面
# 1.点击表单的第一个文本字段
# 2.遍历表单,再每个输入栏键入信息
# 3.点击submit按钮
# 4.用下一组数据重复这个过程
# automatically fills in the form.
import pyautogui,time
# set these to the correct coordinates for your computer.
namefield = (648,319)
submitbutton = (651,817)
submitbuttoncolor = (75,141,249)
submitanotherlink = (760,224)
formdata = [{'name':'alice','fear':'eavppers','source':'wand','robocop':4,'comments':'tell us'},
      {'name':'bog','fear':'eaves','source':'crystal','robocop':4,'comments':'big room'},
      {'name':'kad','fear':'apple','source':'woold','robocop':1,'comments':'nice day'},
      {'name':'cace','fear':'ppers','source':'ball','robocop':5,'comments':'n/a'}
      ]
pyautogui.pause = 0.5
for person in formdata:
  # give the user a chance to kill the script.
  print('>>> 5 second pause to let user press ctrl-c <<<')
  time.sleep(5)
  # wait until the form page has loaded.
  while not pyautogui.pixelmatchescolor(submitbutton[0],submitbutton[1],submitbuttoncolor):
    time.sleep(0.5)
  print('entering %s info...' % (person['name']))
  pyautogui.click(namefield[0],namefield[1])    # 单击第一个文本字段输入位置
  # fill out the name field.
  pyautogui.typewrite(person['name']+'\t')     # 输入该域,并按下 tab 键,将焦点转向下一个输入框
  # fill out the greatest fear(s) field.
  pyautogui.typewrite(person['fear']+'\t')
  # 处理下拉框
  # fill out the source of wizard powers field
  if person['source'] == 'wand':
    pyautogui.typewrite(['down','\t'])
  elif person['source'] == 'crystal':
    pyautogui.typewrite(['down','down','\t'])
  elif person['source'] == 'woold':
    pyautogui.typewrite(['down','down','down','\t'])
  elif person['source'] == 'ball':
    pyautogui.typewrite(['down','down','down','down','\t'])
  # 处理单选按钮
  # fill out the robocop field
  if person['robocop'] == 1:
    pyautogui.typewrite([' ','\t'])
  elif person['robocop'] == 2:
    pyautogui.typewrite(['right','\t'])
  elif person['robocop'] == 3:
    pyautogui.typewrite(['right','right','\t'])
  elif person['robocop'] == 4:
    pyautogui.typewrite(['right','right','right','\t'])
  elif person['robocop'] == 5:
    pyautogui.typewrite(['right','right','right','right','\t'])
  # fill out the additional comments field.
  pyautogui.typewrite(person['comments']+'\t')
  # click submit.
  pyautogui.press('enter')
  # wait until form page has loaded.
  print('clicked submit.')
  time.sleep(5)
  # click the submit another response link.
  pyautogui.click(submitanotherlink[0],submitanotherlink[1])

更多关于python相关内容感兴趣的读者可查看本站专题:《python数据结构与算法教程》、《python socket编程技巧总结》、《python函数使用技巧总结》、《python字符串操作技巧汇总》、《python入门与进阶经典教程》及《python文件与目录操作技巧汇总

希望本文所述对大家python程序设计有所帮助。