当前位置:   article > 正文

python进阶宝典19- pyautogui自动化鼠标和键盘操作_pyautogui进阶

pyautogui进阶

一  pyautogui模块简要说明

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

二  控制鼠标移动与交互

三  屏幕快照与识别比较

四  控制键盘

五  综合例子

具体见以下代码及说明:

  1. ## 使用 pyautogui 模块相关函数,可以模拟鼠标及键盘操作, 完整说明文档见: http://pyautogui.readthedocs.org/
  2. # pip install pyautogui
  3. # 要注意的是,模拟移动鼠标与击键可能太快,导致其他程序跟不上,并且程序可能失去控制,
  4. # 需要掌握如何从问题中恢复,至少要能中止它。
  5. # 防止或恢复GUI自动化问题
  6. # 1) 使用pyautogui.PAUSE设置每个PyAutoGUI函数调用在执行动作后暂停的秒数
  7. # 2) pyautogui自动防故障功能:将鼠标移到屏幕的左上角,来抛出failSafeException异常
  8. import pyautogui
  9. pyautogui.PAUSE = 1
  10. pyautogui.FAILSAFE = True # 启用自动防故障功能
  11. width,height = pyautogui.size() # 屏幕的宽度和高度
  12. pyautogui.position() # 鼠标当前位置
  13. ## 控制鼠标移动
  14. for i in range(10):
  15. pyautogui.moveTo(100,100,duration=0.25) # 移动到 (100,100)
  16. pyautogui.moveTo(200,100,duration=0.25)
  17. pyautogui.moveTo(200,200,duration=0.25)
  18. pyautogui.moveTo(100,200,duration=0.25)
  19. for i in range(10):
  20. pyautogui.moveRel(100,0,duration=0.25) # 从当前位置右移100像素
  21. pyautogui.moveRel(0,100,duration=0.25) # 向下
  22. pyautogui.moveRel(-100,0,duration=0.25) # 向左
  23. pyautogui.moveRel(0,-100,duration=0.25) # 向上
  24. ## 例子:持续获取鼠标位置并更新显示
  25. # 1.获取当前坐标
  26. # 2.在屏幕上打印,并删除之前打印的坐标
  27. # 3.处理异常,并能按键退出
  28. # Displays the mouse cursor's currrent position.
  29. import pyautogui
  30. print('Press Ctrl-C to quit.')
  31. try:
  32. while True:
  33. # Get and print the mouse coordinates.
  34. x,y = pyautogui.position()
  35. positionStr = 'X: '+str(x).rjust(4)+' Y:'+str(y).rjust(4)
  36. pix = pyautogui.screenshot().getpixel((x,y)) # 获取鼠标所在屏幕点的RGB颜色
  37. positionStr += ' RGB:('+str(pix[0]).rjust(3)+','+str(pix[1]).rjust(3)+','+str(pix[2]).rjust(3)+')'
  38. print(positionStr,end='') # end='' 替换了默认的换行
  39. print('\b'*len(positionStr),end='',flush=True) # 连续退格键并刷新,删除之前打印的坐标,就像直接更新坐标效果
  40. except KeyboardInterrupt: # 处理 Ctrl-C 按键
  41. print('\nDone.')
  42. ## 控制鼠标交互
  43. # pyautogui.click() 封装了 pyautogui.mouseDown()和pyautogui.mouseUp(), 这两个函数也可以单独使用
  44. # pyautogui.doubleClick() 双击左键, pyautogui.rightClick() 双击右键,pyautogui.middleClick() 双击中键
  45. import pyautogui
  46. pyautogui.click(10,5) # 在(10,5)单击鼠标,默认左键
  47. pyautogui.click(100,150,button='left')
  48. pyautogui.click(200,250,button='right')
  49. # pyautogui.dragTo() 按键并拖动鼠标移动,参数为坐标,与moveTo相同
  50. # pyautogui.dragRel() 按键并拖动鼠标移动,参数为距离,与moveRel相同
  51. import pyautogui,time
  52. time.sleep(5)
  53. # 这里停顿5秒,用于手工打开windows绘图应用,并选中铅笔或画图工具,让鼠标停留在画图工具的窗口中
  54. # 或使用在线paint (http://sumopaint.com)
  55. pyautogui.click() # click to put drawing program in focus
  56. distance = 200
  57. while distance > 0 :
  58. pyautogui.dragRel(distance,0,duration=0.2) # move right
  59. distance = distance - 5
  60. pyautogui.dragRel(0,distance,duration=0.2) # move down
  61. pyautogui.dragRel(-distance,0,duration=0.2) # move left
  62. distance = distance - 5
  63. pyautogui.dragRel(0,-distance,duration=0.2) # move up
  64. print('Done')
  65. pyautogui.scroll(200) # 鼠标向上滚动200像素
  66. pyautogui.scroll(-100) # 负数向下
  67. import pyperclip
  68. numbers = ''
  69. for i in range(200):
  70. numbers = numbers + str(i) + '\n'
  71. pyperclip.copy(numbers)
  72. print(numbers)
  73. # 这里手动打开一个文本窗口,粘贴
  74. import time,pyautogui
  75. time.sleep(5);pyautogui.scroll(100)
  76. ## 分析屏幕快照
  77. import pyautogui
  78. im = pyautogui.screenshot() # 获取屏幕快照
  79. im.getpixel((50,200)) # (130,135,144)
  80. pyautogui.pixelMatchesColor(50,200,(130,135,144)) # True 可用来判断屏幕是否发生变化
  81. pyautogui.pixelMatchesColor(50,200,(255,135,144)) # False
  82. # 图像定位识别
  83. pyautogui.locateOnScreen('submit.png') # 在屏幕上查找匹配与文件相同的区域--每个区域像素都要相同 左,顶,宽,高
  84. pyautogui.center(pyautogui.locateOnScreen('submit.png')) # 获取匹配图像中心点坐标
  85. pyautogui.click((678,759)) # 点击该区域核心
  86. list(pyautogui.locateAllOnScreen('submit.png')) # 匹配到多处,返回区域list
  87. ## 控制键盘
  88. pyautogui.click(100,100);pyautogui.typewrite('Hello python')
  89. pyautogui.typewrite(['a','b','left','left','X','Y']) # typewrite可传入击键列表,这里输出XYab,left是左箭头
  90. print(pyautogui.KEYBOARD_KEYS) # pyautogui接受的所有可能字符串
  91. pyautogui.press('enter') # 接受按键命令
  92. pyautogui.keyDown('shift');pyautogui.press('4');pyautogui.keyUp('shift') # 输出 $ 符号的按键
  93. #热键组合
  94. pyautogui.keyDown('ctrl')
  95. pyautogui.keyDown('c')
  96. pyautogui.keyUp('c')
  97. pyautogui.keyUp('ctrl')
  98. # 这四句是组合 ctrl-c,类似这种顺序按下,再反序释放的,可以用hotkey()
  99. pyautogui.hotkey('ctrl','c') # 同上面四句,组合键
  100. pyautogui.hotkey('ctrl','alt','shift','s') # Ctrl-Alt-Shift-S 热键组合
  101. ## 综合例子: 自动填表程序
  102. # http://autbor.com/form
  103. # 将电子表格中的大量数据自动输入到另一个应用的表单界面
  104. # 1.点击表单的第一个文本字段
  105. # 2.遍历表单,再每个输入栏键入信息
  106. # 3.点击submit按钮
  107. # 4.用下一组数据重复这个过程
  108. # Automatically fills in the form.
  109. import pyautogui,time
  110. # set these to the correct coordinates for your computer.
  111. nameField = (648,319)
  112. submitButton = (651,817)
  113. submitButtonColor = (75,141,249)
  114. submitAnotherLink = (760,224)
  115. formData = [{'name':'Alice','fear':'eavppers','source':'wand','robocop':4,'comments':'Tell us'},
  116. {'name':'Bog','fear':'eaves','source':'crystal','robocop':4,'comments':'Big room'},
  117. {'name':'Kad','fear':'apple','source':'woold','robocop':1,'comments':'Nice day'},
  118. {'name':'Cace','fear':'ppers','source':'ball','robocop':5,'comments':'n/a'}
  119. ]
  120. pyautogui.PAUSE = 0.5
  121. for person in formData:
  122. # Give the user a chance to kill the script.
  123. print('>>> 5 SECOND PAUSE TO LET USER PRESS CTRL-C <<<')
  124. time.sleep(5)
  125. # Wait until the form page has loaded.
  126. while not pyautogui.pixelMatchesColor(submitButton[0],submitButton[1],submitButtonColor):
  127. time.sleep(0.5)
  128. print('Entering %s info...' % (person['name']))
  129. pyautogui.click(nameField[0],nameField[1]) # 单击第一个文本字段输入位置
  130. # Fill out the Name field.
  131. pyautogui.typewrite(person['name']+'\t') # 输入该域,并按下 tab 键,将焦点转向下一个输入框
  132. # Fill out the Greatest Fear(s) field.
  133. pyautogui.typewrite(person['fear']+'\t')
  134. # 处理下拉框
  135. # Fill out the Source of Wizard Powers Field
  136. if person['source'] == 'wand':
  137. pyautogui.typewrite(['down','\t'])
  138. elif person['source'] == 'crystal':
  139. pyautogui.typewrite(['down','down','\t'])
  140. elif person['source'] == 'woold':
  141. pyautogui.typewrite(['down','down','down','\t'])
  142. elif person['source'] == 'ball':
  143. pyautogui.typewrite(['down','down','down','down','\t'])
  144. # 处理单选按钮
  145. # Fill out the RoboCop field
  146. if person['robocop'] == 1:
  147. pyautogui.typewrite([' ','\t'])
  148. elif person['robocop'] == 2:
  149. pyautogui.typewrite(['right','\t'])
  150. elif person['robocop'] == 3:
  151. pyautogui.typewrite(['right','right','\t'])
  152. elif person['robocop'] == 4:
  153. pyautogui.typewrite(['right','right','right','\t'])
  154. elif person['robocop'] == 5:
  155. pyautogui.typewrite(['right','right','right','right','\t'])
  156. # Fill out the Additional Comments field.
  157. pyautogui.typewrite(person['comments']+'\t')
  158. # Click Submit.
  159. pyautogui.press('enter')
  160. # Wait until form page has loaded.
  161. print('Clicked submit.')
  162. time.sleep(5)
  163. # Click the Submit another response link.
  164. pyautogui.click(submitAnotherLink[0],submitAnotherLink[1])

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/121121
推荐阅读
相关标签
  

闽ICP备14008679号