溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python使用pyautogui模塊實現(xiàn)自動化鼠標(biāo)和鍵盤操作示例

發(fā)布時間:2020-09-17 17:39:22 來源:腳本之家 閱讀:347 作者:周雄偉 欄目:開發(fā)技術(shù)

本文實例講述了Python使用pyautogui模塊實現(xiàn)自動化鼠標(biāo)和鍵盤操作。分享給大家供大家參考,具體如下:

一、pyautogui模塊簡要說明

## 使用 pyautogui 模塊相關(guān)函數(shù),可以模擬鼠標(biāo)及鍵盤操作, 完整說明文檔見: http://pyautogui.readthedocs.org/
# pip install pyautogui
# 要注意的是,模擬移動鼠標(biāo)與擊鍵可能太快,導(dǎo)致其他程序跟不上,并且程序可能失去控制,
# 需要掌握如何從問題中恢復(fù),至少要能中止它。
# 防止或恢復(fù)GUI自動化問題
# 1) 使用pyautogui.PAUSE設(shè)置每個PyAutoGUI函數(shù)調(diào)用在執(zhí)行動作后暫停的秒數(shù)
# 2) pyautogui自動防故障功能:將鼠標(biāo)移到屏幕的左上角,來拋出failSafeException異常

二、控制鼠標(biāo)移動與交互

三、屏幕快照與識別比較

四、控制鍵盤

五、綜合例子

具體見以下代碼及說明:

## 使用 pyautogui 模塊相關(guān)函數(shù),可以模擬鼠標(biāo)及鍵盤操作, 完整說明文檔見: http://pyautogui.readthedocs.org/
# pip install pyautogui
# 要注意的是,模擬移動鼠標(biāo)與擊鍵可能太快,導(dǎo)致其他程序跟不上,并且程序可能失去控制,
# 需要掌握如何從問題中恢復(fù),至少要能中止它。
# 防止或恢復(fù)GUI自動化問題
#  1) 使用pyautogui.PAUSE設(shè)置每個PyAutoGUI函數(shù)調(diào)用在執(zhí)行動作后暫停的秒數(shù)
#  2) pyautogui自動防故障功能:將鼠標(biāo)移到屏幕的左上角,來拋出failSafeException異常
import pyautogui
pyautogui.PAUSE = 1
pyautogui.FAILSAFE = True      # 啟用自動防故障功能
width,height = pyautogui.size()   # 屏幕的寬度和高度
pyautogui.position()        # 鼠標(biāo)當(dāng)前位置
## 控制鼠標(biāo)移動
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)    # 從當(dāng)前位置右移100像素
  pyautogui.moveRel(0,100,duration=0.25)    # 向下
  pyautogui.moveRel(-100,0,duration=0.25)   # 向左
  pyautogui.moveRel(0,-100,duration=0.25)   # 向上
## 例子:持續(xù)獲取鼠標(biāo)位置并更新顯示
# 1.獲取當(dāng)前坐標(biāo)
# 2.在屏幕上打印,并刪除之前打印的坐標(biāo)
# 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))  # 獲取鼠標(biāo)所在屏幕點的RGB顏色
    positionStr += ' RGB:('+str(pix[0]).rjust(3)+','+str(pix[1]).rjust(3)+','+str(pix[2]).rjust(3)+')'
    print(positionStr,end='')           # end='' 替換了默認(rèn)的換行
    print('\b'*len(positionStr),end='',flush=True) # 連續(xù)退格鍵并刷新,刪除之前打印的坐標(biāo),就像直接更新坐標(biāo)效果
except KeyboardInterrupt:               # 處理 Ctrl-C 按鍵
  print('\nDone.')
## 控制鼠標(biāo)交互
# pyautogui.click() 封裝了 pyautogui.mouseDown()和pyautogui.mouseUp(), 這兩個函數(shù)也可以單獨使用
# pyautogui.doubleClick() 雙擊左鍵, pyautogui.rightClick() 雙擊右鍵,pyautogui.middleClick() 雙擊中鍵
import pyautogui
pyautogui.click(10,5)           # 在(10,5)單擊鼠標(biāo),默認(rèn)左鍵
pyautogui.click(100,150,button='left')
pyautogui.click(200,250,button='right')
# pyautogui.dragTo()  按鍵并拖動鼠標(biāo)移動,參數(shù)為坐標(biāo),與moveTo相同
# pyautogui.dragRel()  按鍵并拖動鼠標(biāo)移動,參數(shù)為距離,與moveRel相同
import pyautogui,time
time.sleep(5)
# 這里停頓5秒,用于手工打開windows繪圖應(yīng)用,并選中鉛筆或畫圖工具,讓鼠標(biāo)停留在畫圖工具的窗口中
# 或使用在線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)     # 鼠標(biāo)向上滾動200像素
pyautogui.scroll(-100)    #   負(fù)數(shù)向下
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 可用來判斷屏幕是否發(fā)生變化
pyautogui.pixelMatchesColor(50,200,(255,135,144))  # False
# 圖像定位識別
pyautogui.locateOnScreen('submit.png')  # 在屏幕上查找匹配與文件相同的區(qū)域--每個區(qū)域像素都要相同 左,頂,寬,高
pyautogui.center(pyautogui.locateOnScreen('submit.png')) # 獲取匹配圖像中心點坐標(biāo)
pyautogui.click((678,759))        # 點擊該區(qū)域核心
list(pyautogui.locateAllOnScreen('submit.png'))  # 匹配到多處,返回區(qū)域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
# 將電子表格中的大量數(shù)據(jù)自動輸入到另一個應(yīng)用的表單界面
# 1.點擊表單的第一個文本字段
# 2.遍歷表單,再每個輸入欄鍵入信息
# 3.點擊submit按鈕
# 4.用下一組數(shù)據(jù)重復(fù)這個過程
# 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 鍵,將焦點轉(zhuǎn)向下一個輸入框
  # 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])

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》

希望本文所述對大家Python程序設(shè)計有所幫助。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI