pyautogui庫的使用及說明
一、前言
PyAutoGUI 讓您的 Python 腳本控制鼠標和鍵盤以自動與其他應用程序交互。
| 函數(shù)名 | 功能 | |
|---|---|---|
| 基本 | pyautogui.size() | 返回包含分辨率的元組 |
| pyautogui.PAUSE | 每個函數(shù)的停頓時間,默認0.1s | |
| pyautogui.FAILSAFE | 是否開啟防故障功能,默認True | |
| 鍵盤 | pyautogui.press('鍵盤字符') | 按下并松開指定按鍵 |
| pyautogui.keyDown('鍵盤字符') | 按下指定按鍵 | |
| pyautogui.keyUp('鍵盤字符') | 松開指定按鍵 | |
| pyautogui.hotkey('鍵盤字符1', '鍵盤字符2') | 按下多個指定鍵 | |
| 鼠標 | pyautogui.position() | 返回當前鼠標當前位置的元組 |
| pyautogui.moveTo(x,y,duration=1) | 按絕對位置移動鼠標并設置移動時間 | |
| pyautogui.moveRel(x_rel,y_rel,duration=4) | 按相對位置移動鼠標并設置移動時間 | |
| pyautogui.dragTo(x, y, duration=1) | 按絕對位置拖動鼠標并設置移動時間 | |
| pyautogui.dragRel(x_rel, y_rel, duration=4) | 按相對位置拖動鼠標并設置移動時間 | |
| pyautogui.click(x, y) | 鼠標點擊指定位置,默認左鍵 | |
| pyautogui.click(x, y, button='left') | 鼠標單擊左鍵 | |
| pyautogui.click(x, y, button='right') | 鼠標單擊右鍵 | |
| pyautogui.click(x, y, button='middle') | 鼠標單擊中間,即滾輪 | |
| pyautogui.doubleClick(10,10) | 鼠標左鍵雙擊指定位置 | |
| pyautogui.rightClick(10,10) | 鼠標右鍵雙擊指定位置 | |
| pyautogui.middleClick(10,10) | 鼠標中鍵雙擊指定位置 | |
| pyautogui.scroll(10) | 鼠標滾輪向上滾動10個單位 |
press(), keyDowm(),keyUp(),hotKey()支持的有效字符串列表如下:
| 類別 | |
|---|---|
| 字母 | 'a', 'b', 'c', 'd', 'e','f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' |
| 數(shù)字 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' |
| 符號 | '\t', '\n', '\r', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', , ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', |
| F鍵 | 'f1', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f2', 'f20', 'f21', 'f22', 'f23', 'f24', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', |
| 數(shù)字鍵盤 | 'num0', 'num1', 'num2', 'num3', 'num4', 'num5', 'num6', 'num7', 'num8', 'num9', |
| 其他 | 'accept', 'add', 'alt', 'altleft', 'altright', 'apps', 'backspace', 'browserback', 'browserfavorites', 'browserforward', 'browserhome', 'browserrefresh', 'browsersearch', 'browserstop', 'capslock', 'clear', 'convert', 'ctrl', 'ctrlleft', 'ctrlright', 'decimal', 'del', 'delete', 'divide', 'down', 'end', 'enter', 'esc', 'escape', 'execute', 'final', 'fn', 'hanguel', 'hangul', 'hanja', 'help', 'home', 'insert', 'junja', 'kana', 'kanji', 'launchapp1', 'launchapp2', 'launchmail', 'launchmediaselect', 'left', 'modechange', 'multiply', 'nexttrack', 'nonconvert', , 'numlock', 'pagedown', 'pageup', 'pause', 'pgdn', 'pgup', 'playpause', 'prevtrack', 'print', 'printscreen', 'prntscrn', 'prtsc', 'prtscr', 'return', 'right', 'scrolllock', 'select', 'separator', 'shift', 'shiftleft', 'shiftright', 'sleep', 'space', 'stop', 'subtract', 'tab', 'up', 'volumedown', 'volumemute', 'volumeup', 'win', 'winleft', 'winright', 'yen', 'command', 'option', 'optionleft', 'optionright' |
二、基本使用
0. 坐標說明

坐標的距離通過像素計算,如果你的屏幕分辨率是1920 x 1080,右下角的像素將是1919, 1079(因為坐標從0開始,而不是1)。
1. 一般功能
① 獲取鼠標當前坐標(以像素為單位)
pyautogui.position()
② 獲取屏幕尺寸
pyautogui.size()
③ 判斷指定坐標 (x,y) 是否在屏幕內
pyautogui.onScreen(x, y)
2. 故障保險
① 控制調用 PyAutoGUI 后的暫停時間(單位:秒)
pyautogui.PAUSE = 2.5
② 當故障安全模式為True時,將鼠標移動到左上角將引發(fā)一個 pyautogui.FailSafeException 從而中斷程序(默認為:True)
pyautogui.FAILSAFE = True
3. 鼠標控制
① 在 num_Second 秒內將鼠標移動到指定坐標
pyautogui.moveTo(x, y, duration=num_seconds)
② 相對于鼠標當前位置移動鼠標
pyautogui.moveRel(xOffset, yOffset, duration=num_seconds)
③ 在 num_Second 秒內將鼠標拖動到指定坐標
pyautogui.dragTo(x, y, duration=num_seconds)
④ 相對于鼠標當前位置拖動鼠標
pyautogui.dragRel(xOffset, yOffset, duration=num_seconds)
⑤ 調用click()只會讓鼠標在當前位置用左鍵單擊一次,但關鍵字參數(shù)可以改變這一點,button關鍵字參數(shù)可以'left'是、'middle'或'right'。
pyautogui.click(x=moveToX, y=moveToY, clicks=num_of_clicks, interval=secs_between_clicks,button = 'left')
⑥ 單獨調用指定鍵的點擊事件
pyautogui.rightClick(x=moveToX, y=moveToY) pyautogui.middleClick(x=moveToX, y=moveToY) pyautogui.doubleClick(x=moveToX, y=moveToY) pyautogui.tripleClick(x=moveToX, y=moveToY)
⑦ 正數(shù)控制滾輪將向上滾動,負數(shù)控制滾輪將向下滾動
pyautogui.scroll(amount_to_scroll, x=moveToX, y=moveToY)
⑧ 單獨調用鼠標的按下和松開事件
pyautogui.mouseDown(x=moveToX, y=moveToY, button='left') pyautogui.mouseUp(x=moveToX, y=moveToY, button='left')
4. 鍵盤控制
① 在鍵盤光標處輸入指定文本
pyautogui.typewrite('Hello world!\n', interval=secs_between_keys)② 傳遞密鑰等
pyautogui.typewrite(['a', 'b', 'c', 'left', 'backspace', 'enter', 'f1'], interval=secs_between_keys)
③ 鍵盤熱鍵(如Ctrl-S或Ctrl-Shift-1)可以通過將鍵名稱列表傳遞給hotkey()來完成:
pyautogui.hotkey('ctrl', 'c') # ctrl-c 復制
pyautogui.hotkey('ctrl', 'v') # ctrl-v 粘貼④ 單獨調用按鈕的點擊事件和松開事件:
pyautogui.keyDown(鍵名稱) pyautogui.keyUp(鍵名稱)
5. 消息框函數(shù)
如果您需要暫停程序直到用戶單擊確定,或者想要向用戶顯示一些信息,則可使用消息框函數(shù)。
pyautogui.alert('這將顯示帶有確定按鈕的文本。')
pyautogui.confirm('這將顯示帶有確定和取消按鈕的文本。')
pyautogui.prompt('這樣用戶就可以輸入一個字符串,然后按確定。')6. 截圖功能
① PyAutoGUI使用Pillow/PIL來存儲與圖像相關的數(shù)據(jù)。
pyautogui.screenshot() # 返回Pillow/PIL圖像對象
pyautogui.screenshot('foo.png') # 返回Pillow/PIL圖像對象,并將其保存到文件② 返回在當前界面找到第一個圖標位置的元組 (left, top, width, height)
pyautogui.locateOnScreen('looksLikeThis.png') ③ LocateAllOnScreen()函數(shù)將返回屏幕上找到的所有位置的生成器。
>>> for i in pyautogui.locateAllOnScreen('looksLikeThis.png')
...
...
(863, 117, 70, 13)
(623, 137, 70, 13)
(853, 577, 70, 13)
(883, 617, 70, 13)
(973, 657, 70, 13)
(933, 877, 70, 13)>>> list(pyautogui.locateAllOnScreen('looksLikeThis.png'))
[(863, 117, 70, 13), (623, 137, 70, 13), (853, 577, 70, 13), (883, 617, 70, 13), (973, 657, 70, 13), (933, 877, 70, 13)]
④ 返回屏幕上圖像所在位置的XY坐標。
>>> pyautogui.locateCenterOnScreen('looksLikeThis.png') # 返回中心坐標 (898,423)
三、進階教程
1. 鼠標控制
1.1 pyautogui.size()
返回屏幕的分辨率大小,返回類型為元組。
>>> pyautogui.size() (1920, 1080)
1.2 pyautogui.position()
返回鼠標光標的當前位置,返回類型為元組。
>>> pyautogui.position() (187, 567)
1.3 pyautogui.onScreen()
判斷指定位置是否在屏幕內,返回類型為布爾型。
>>> pyautogui.onScreen(0, 0) True >>> pyautogui.onScreen(0, -1) False >>> pyautogui.onScreen(0, 99999999) False
1.4 pyautogui.move()
移動鼠標光標以當前位置為起點移動指定距離,如果輸入 None 則為當前位置的X或Y。
>>> pyautogui.moveTo(100, 200) # moves mouse to X of 100, Y of 200. >>> pyautogui.moveTo(None, 500) # moves mouse to X of 100, Y of 500. >>> pyautogui.moveTo(600, None) # moves mouse to X of 600, Y of 500.
第三個參數(shù)可以設置鼠標移動到指定位置所花費的時間。
>>> pyautogui.moveTo(100, 200, 2) # moves mouse to X of 100, Y of 200 over 2 seconds
1.5 pyautogui.moveTo()
與move()類似,此函數(shù)可以按照絕對位置移動鼠標。
>>> pyautogui.moveTo(100, 200) # moves mouse to X of 100, Y of 200. >>> pyautogui.move(0, 50) # move the mouse down 50 pixels. >>> pyautogui.move(-30, 0) # move the mouse left 30 pixels. >>> pyautogui.move(-30, None) # move the mouse left 30 pixels.
1.6 pyautogui.drag()
以相對位置拖動鼠標,可指定拖動時按住某個鍵:'left', 'middle', 'right'。
>>> pyautogui.dragTo(100, 200, button='left') # drag mouse to X of 100, Y of 200 while holding down left mouse button >>> pyautogui.dragTo(300, 400, 2, button='left') # drag mouse to X of 300, Y of 400 over 2 seconds while holding down left mouse button >>> pyautogui.drag(30, 0, 2, button='right') # drag the mouse left 30 pixels over 2 seconds while holding down the right mouse button
1.7 pyautogui.dragto()
以絕對位置拖動鼠標,可指定拖動時按住某個鍵:'left', 'middle', 'right'。
1.8 pyautogui.click()
模擬在鼠標當前位置單擊鼠標左鍵。
>>> pyautogui.click() # click the mouse >>> pyautogui.click(x=100, y=200) # move to 100, 200, then click the left mouse button. >>> pyautogui.click(button='right') # right-click the mouse >>> pyautogui.click(clicks=2) # double-click the left mouse button >>> pyautogui.click(clicks=2, interval=0.25) # double-click the left mouse button, but with a quarter second pause in between clicks >>> pyautogui.click(button='right', clicks=3, interval=0.25) ## triple-click the right mouse button with a quarter second pause in between clicks
1.9 pyautogui.doubleClick()
模擬雙擊鼠標左鍵。
>>> pyautogui.doubleClick() # perform a left-button double click
1.10 pyautogui.tripleClick()
1.11 pyautogui.rightClick()
1.12 pyautogui.mouseDown()
按下鼠標
>>> pyautogui.mouseDown(); pyautogui.mouseUp() # does the same thing as a left-button mouse click >>> pyautogui.mouseDown(button='right') # press the right button down >>> pyautogui.mouseUp(button='right', x=100, y=200) # move the mouse to 100, 200, then release the right button up.
1.13 pyautogui.mouseUp()
松開鼠標
1.14 pyautogui.scroll()
滾動鼠標滾輪
>>> pyautogui.scroll(10) # scroll up 10 "clicks" >>> pyautogui.scroll(-10) # scroll down 10 "clicks" >>> pyautogui.scroll(10, x=100, y=100) # move mouse cursor to 100, 200, then scroll up 10 "clicks"
1.15 pyautogui.hscroll()
水平滾動鼠標
>>> pyautogui.hscroll(10) # scroll right 10 "clicks" >>> pyautogui.hscroll(-10) # scroll left 10 "clicks"
1.16 pyautogui.vscroll()
垂直滾動鼠標
2. 鍵盤控制
2.1 pyautogui.write()
鍵入指定字符串
>>> pyautogui.write('Hello world!') # prints out "Hello world!" instantly
>>> pyautogui.write('Hello world!', interval=0.25) # prints out "Hello world!" with a quarter second delay after each character2.2 pyautogui.press()
按一次指定鍵
>>> pyautogui.press('enter') # press the Enter key
>>> pyautogui.press('f1') # press the F1 key
>>> pyautogui.press('left') # press the left arrow key2.4 pyautogui.keyDown()
按下指定鍵
2.5 pyautogui.keyUp()
松開指定鍵
2.6 pyautogui.hold()
保持按住某個鍵并松開
>>> with pyautogui.hold('shift'):
pyautogui.press(['left', 'left', 'left'])2.7 pyautogui.hotkey()
實現(xiàn)快捷鍵
>>> pyautogui.hotkey('ctrl', 'shift', 'esc')3. 消息框函數(shù)
PyAutoGUI利用PyMsgBox中的消息框函數(shù)提供了一種跨平臺的純Python方式來顯示JavaScript樣式的消息框。提供了四個消息框函數(shù):
3.1 pyautogui.alert()
>>> alert(text='', title='', button='OK')
顯示一個簡單的消息框,其中包含文本和一個確定按鈕。返回單擊的按鈕的文本。
3.2 pyautogui.confirm()
>>> confirm(text='', title='', buttons=['OK', 'Cancel'])
顯示帶有確定和取消按鈕的消息框。可以自定義按鈕的數(shù)量和文本。返回單擊的按鈕的文本。
3.3 pyautogui.prompt()
>>> prompt(text='', title='' , default='')
顯示帶有文本輸入和確定和取消按鈕的消息框。返回輸入的文本,如果單擊了取消,則返回None。
3.4 pyautogui.password()
>>> password(text='', title='', default='', mask='*')
顯示帶有文本輸入和確定和取消按鈕的消息框。鍵入的字符顯示為*。返回輸入的文本,如果單擊了取消,則返回None。
4. 截圖功能
PyAutoGUI可以截取屏幕截圖,將它們保存到文件中,并在屏幕內定位圖像。
例如,如果您有一個需要單擊的按鈕的小圖像,并且想要在屏幕上找到它,這是很有用的。這些功能由隨PyAutoGUI一起安裝的PyScreeze模塊提供。
4.1 pyautogui.screenshot()
調用screenshot()將返回一個 Image 對象(有關詳細信息,請參閱 Pillow 或 PIL 模塊文檔)。傳遞文件名字符串會將屏幕截圖保存到文件中,并將其作為 Image 對象返回。
>>> import pyautogui
>>> im1 = pyautogui.screenshot()
>>> im2 = pyautogui.screenshot('my_screenshot.png') # 捕獲并保存到本地
>>> im3 = pyautogui.screenshot(region=(0,0, 300, 400)) # 捕獲指定范圍4.2 pyautogui.locateOnScreen()
獲取屏幕坐標。返回值是一個 4 整數(shù)元組:(left, top, width, height)??梢詡鬟f此元組center()以獲取此區(qū)域中心的 X 和 Y 坐標。
4.3 pyautogui.locateCenterOnScreen()
返回在屏幕上找到的第一個實例的中心的 (x, y) 坐標。
4.4 pyautogui.locateAllOnScreen()
返回一個生成器,該生成器生成(左、上、寬、高)元組。
4.5 pyautogui.pixel()
獲取屏幕截圖中像素的 RGB 顏色
>>> import pyautogui >>> im = pyautogui.screenshot() >>> im.getpixel((100, 200)) (130, 135, 144)
4.6 pyautogui.pixelMatchesColor()
驗證單個像素是否與給定像素匹配。
>>> import pyautogui >>> pyautogui.pixelMatchesColor(100, 200, (130, 135, 144)) True >>> pyautogui.pixelMatchesColor(100, 200, (0, 0, 0)) False
四、實例
1. 自動點擊網(wǎng)頁指定圖標
參考鏈接:
import pyautogui
import time
while True:
# 本頁存在指定圖標
if pyautogui.locateOnScreen('icon.png'):
time.sleep(0.5) # 等待 0.5 秒
position = pyautogui.center(pyautogui.locateOnScreen('icon.png')) # 尋找圖標的中心
pyautogui.click(position) # 點擊
# 本頁不存在指定圖標
else:
pyautogui.scroll(-500) # 滾動鼠標,進入下一頁
2. 獲取鼠標當前位置
# 案例獲取鼠標的位置,方便復制我們定位的鼠標坐標點到代碼中
import pyautogui
import time
# 獲取鼠標位置
def get_mouse_positon():
time.sleep(5) # 準備時間
print('開始獲取鼠標位置')
try:
for i in range(10):
# Get and print the mouse coordinates.
x, y = pyautogui.position()
positionStr = '鼠標坐標點(X,Y)為:{},{}'.format(str(x).rjust(4), 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)
time.sleep(0.5) # 停頓時間
except:
print('獲取鼠標位置失敗')
if __name__ == "__main__":
get_mouse_positon()
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python cookbook(字符串與文本)針對任意多的分隔符拆分字符串操作示例
這篇文章主要介紹了Python cookbook(字符串與文本)針對任意多的分隔符拆分字符串操作,結合實例形式分析了Python使用split()及正則表達式進行字符串拆分操作相關實現(xiàn)技巧,需要的朋友可以參考下2018-04-04

