欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2018年09月04日 10:03:38   作者:周雄偉  
這篇文章主要介紹了Python使用pyautogui模塊實現(xiàn)自動化鼠標(biāo)和鍵盤操作,簡單描述了pyautogui模塊的功能,并結(jié)合實例形式較為詳細(xì)的分析了Python使用pyautogui模塊實現(xiàn)鼠標(biāo)與鍵盤自動化操作相關(guān)技巧,需要的朋友可以參考下

本文實例講述了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è)計有所幫助。

相關(guān)文章

  • Python中利用sorted()函數(shù)排序的簡單教程

    Python中利用sorted()函數(shù)排序的簡單教程

    這篇文章主要介紹了Python中利用sorted()函數(shù)排序的簡單教程,sorted()函數(shù)有返回值,在Python的排序?qū)崿F(xiàn)中發(fā)揮著相當(dāng)重要的作用,需要的朋友可以參考下
    2015-04-04
  • mac下如何將python2.7改為python3

    mac下如何將python2.7改為python3

    這篇文章主要介紹了mac下如何將python2.7改為python3,本文分步驟給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-07-07
  • Pandas中`ValueError: cannot reindex from a duplicate axis`錯誤分析及解決辦法

    Pandas中`ValueError: cannot reindex from 

    在Pandas中,ValueError: cannot reindex from a duplicate axis錯誤通常發(fā)生在嘗試對包含重復(fù)索引的DataFrame或Series進(jìn)行重新索引(reindex)時,所以本文介紹了Pandas中`ValueError: cannot reindex from a duplicate axis`錯誤分析及解決辦法,需要的朋友可以參考下
    2024-07-07
  • python-xpath獲取html文檔的部分內(nèi)容

    python-xpath獲取html文檔的部分內(nèi)容

    這篇文章主要介紹了python-xpath獲取html文檔的部分內(nèi)容,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • Python中的線程操作模塊(oncurrent)

    Python中的線程操作模塊(oncurrent)

    這篇文章介紹了Python中的線程操作模塊(oncurrent),文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-05-05
  • 基于Pydantic封裝的通用模型在API請求驗證中的應(yīng)用詳解

    基于Pydantic封裝的通用模型在API請求驗證中的應(yīng)用詳解

    這篇文章主要介紹了基于Pydantic封裝的通用模型在API請求驗證中的應(yīng)用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪
    2023-05-05
  • python中numpy?常用操作總結(jié)

    python中numpy?常用操作總結(jié)

    這篇文章主要介紹了python中numpy常用操作總結(jié),NumPy是Python語言的一個擴(kuò)充程序庫,支持大量高維度數(shù)組與矩陣運(yùn)算,此外也針對數(shù)組運(yùn)算提供大量的數(shù)學(xué)函數(shù)庫
    2022-09-09
  • python字典的setdefault的巧妙用法

    python字典的setdefault的巧妙用法

    這篇文章主要介紹了python字典的setdefault的巧妙用法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08
  • Python調(diào)用Pandas實現(xiàn)Excel讀取

    Python調(diào)用Pandas實現(xiàn)Excel讀取

    這篇文章主要為大家介紹了在Python中如何調(diào)用Pandas實現(xiàn)Excel文件的讀取,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下
    2022-04-04
  • python利用socketserver實現(xiàn)并發(fā)套接字功能

    python利用socketserver實現(xiàn)并發(fā)套接字功能

    這篇文章主要為大家詳細(xì)介紹了python利用socketserver實現(xiàn)并發(fā)套接字功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-01-01

最新評論