一:前置操作
自動防故障 pyautogui.FAILSAFE = False # 默認為True,這項功能意味着:當鼠標的指針在屏幕的最左上方,程序會報錯;目的是為了防止程序無法停止 停頓功能 pyautogui.PAUSE = 1 # 所有pyautogui的指令都要暫停一秒;其他指令不會停頓;這樣做,可以防止鍵盤鼠標操作太快; 點是否在屏幕上 pyautogui.onScreen(x, y) # 結果為true
二:鼠標操作
屏幕分辨率,鼠標位置 pyautogui.size() # 返回元組 pyautogui.position() 鼠標移動 pyautogui.moveTo(100,300,duration=1) # 過程用時1秒 pyautogui.moveRel(50, 0, duration=0.25) # 從當前位置,右移50像素 鼠標點擊 pyautogui.click(10, 20, 2, 0.25, button='left') # 通用方法,參數:坐標 點擊次數,點擊時間間隔,點擊左右中鍵,移動到坐標時間等 pyautogui.doubleClick() # 當前位置左擊兩下,參數:坐標 點擊時間間隔,點擊左右中鍵,移動到坐標時間等 pyautogui.mouseDown() mouseUp leftClick rightClick middleClick # 鼠標按下 鼠標松開 左擊 右擊 中擊 鼠標拖拽 pyautogui.dragTo(100, 200, button='left') # 參數:坐標 點擊左右中鍵,移動到坐標時間等 pyautogui.dragRel(0, -60, duration=0.2) 鼠標滾輪 pyautogui.scroll(clicks=10, x=None, y=None) # 先移動到(100,100)再向上滾動10格
三:鍵盤操作
pyautogui.typewrite('Hello world!', interval=0.0) # 每次輸入間隔0.25秒,輸入Hello world! pyautogui.press('enter') # 按下並松開(輕敲)回車鍵, 參數可以是列表['left', 'left', 'left', 'left'] pyautogui.hotkey('ctrl', 'v') # 組合按鍵(Ctrl+V) pyautogui.keyDown('shift') keyUp pyautogui.KEYBOARD_KEYS 按鍵名稱列表
四:彈窗處理
提示彈窗 pyautogui.alert(text='要開始程序么?', title='請求框', button='OK') # 點擊按鈕或者關閉窗口都返回button的值。 選擇彈窗 pyautogui.confirm(text='', title='', buttons=['OK', 'Cancel']) # OK和Cancel按鈕的消息彈窗,返回點擊按鈕的值,關閉窗口返回None(或者Cancel) 輸入彈窗 pyautogui.prompt(text='', title='', default='') # 返回輸入的值(按ok)或者None (按cancel) pyautogui.password(text='', title='', default='', mask='*') # 同上,輸入顯示為*
五:圖像處理
截屏 pyautogui.screenshot(r'C:\screenshot.png', region=(0, 0, 300, 400)) # imageFilename=None, region=None,返回PIL.Image.Image 取色 pix = pyautogui.pixel(220, 200) # 獲取坐標(220,200)所在屏幕點的RGB顏色,返回三個元素的元組 點匹配色 pyautogui.pixelMatchesColor(100, 200, (255, 255, 245), tolerance=10) # tolerance參數紅、綠、藍誤差范圍 返回True或者False 找圖 pyautogui.locateOnScreen(r'C:\screenshot.png') # 返回 Box(left=0, top=0, width=300, height=400),可以用pyautogui.center(a)返回中心坐標 x, y = pyautogui.locateCenterOnScreen(r'C:\screenshot.png') # 取得圖中心坐標 pyautogui.locateAllOnScreen(r'C:\screenshot.png')) # 返回Box對象列表