pyautogui庫(kù)的使用及說(shuō)明
一、前言
PyAutoGUI 讓您的 Python 腳本控制鼠標(biāo)和鍵盤以自動(dòng)與其他應(yīng)用程序交互。
| 函數(shù)名 | 功能 | |
|---|---|---|
| 基本 | pyautogui.size() | 返回包含分辨率的元組 |
| pyautogui.PAUSE | 每個(gè)函數(shù)的停頓時(shí)間,默認(rèn)0.1s | |
| pyautogui.FAILSAFE | 是否開(kāi)啟防故障功能,默認(rèn)True | |
| 鍵盤 | pyautogui.press('鍵盤字符') | 按下并松開(kāi)指定按鍵 |
| pyautogui.keyDown('鍵盤字符') | 按下指定按鍵 | |
| pyautogui.keyUp('鍵盤字符') | 松開(kāi)指定按鍵 | |
| pyautogui.hotkey('鍵盤字符1', '鍵盤字符2') | 按下多個(gè)指定鍵 | |
| 鼠標(biāo) | pyautogui.position() | 返回當(dāng)前鼠標(biāo)當(dāng)前位置的元組 |
| pyautogui.moveTo(x,y,duration=1) | 按絕對(duì)位置移動(dòng)鼠標(biāo)并設(shè)置移動(dòng)時(shí)間 | |
| pyautogui.moveRel(x_rel,y_rel,duration=4) | 按相對(duì)位置移動(dòng)鼠標(biāo)并設(shè)置移動(dòng)時(shí)間 | |
| pyautogui.dragTo(x, y, duration=1) | 按絕對(duì)位置拖動(dòng)鼠標(biāo)并設(shè)置移動(dòng)時(shí)間 | |
| pyautogui.dragRel(x_rel, y_rel, duration=4) | 按相對(duì)位置拖動(dòng)鼠標(biāo)并設(shè)置移動(dòng)時(shí)間 | |
| pyautogui.click(x, y) | 鼠標(biāo)點(diǎn)擊指定位置,默認(rèn)左鍵 | |
| pyautogui.click(x, y, button='left') | 鼠標(biāo)單擊左鍵 | |
| pyautogui.click(x, y, button='right') | 鼠標(biāo)單擊右鍵 | |
| pyautogui.click(x, y, button='middle') | 鼠標(biāo)單擊中間,即滾輪 | |
| pyautogui.doubleClick(10,10) | 鼠標(biāo)左鍵雙擊指定位置 | |
| pyautogui.rightClick(10,10) | 鼠標(biāo)右鍵雙擊指定位置 | |
| pyautogui.middleClick(10,10) | 鼠標(biāo)中鍵雙擊指定位置 | |
| pyautogui.scroll(10) | 鼠標(biāo)滾輪向上滾動(dòng)10個(gè)單位 |
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' |
| 符號(hào) | '\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. 坐標(biāo)說(shuō)明

坐標(biāo)的距離通過(guò)像素計(jì)算,如果你的屏幕分辨率是1920 x 1080,右下角的像素將是1919, 1079(因?yàn)樽鴺?biāo)從0開(kāi)始,而不是1)。
1. 一般功能
① 獲取鼠標(biāo)當(dāng)前坐標(biāo)(以像素為單位)
pyautogui.position()
② 獲取屏幕尺寸
pyautogui.size()
③ 判斷指定坐標(biāo) (x,y) 是否在屏幕內(nèi)
pyautogui.onScreen(x, y)
2. 故障保險(xiǎn)
① 控制調(diào)用 PyAutoGUI 后的暫停時(shí)間(單位:秒)
pyautogui.PAUSE = 2.5
② 當(dāng)故障安全模式為True時(shí),將鼠標(biāo)移動(dòng)到左上角將引發(fā)一個(gè) pyautogui.FailSafeException 從而中斷程序(默認(rèn)為:True)
pyautogui.FAILSAFE = True
3. 鼠標(biāo)控制
① 在 num_Second 秒內(nèi)將鼠標(biāo)移動(dòng)到指定坐標(biāo)
pyautogui.moveTo(x, y, duration=num_seconds)
② 相對(duì)于鼠標(biāo)當(dāng)前位置移動(dòng)鼠標(biāo)
pyautogui.moveRel(xOffset, yOffset, duration=num_seconds)
③ 在 num_Second 秒內(nèi)將鼠標(biāo)拖動(dòng)到指定坐標(biāo)
pyautogui.dragTo(x, y, duration=num_seconds)
④ 相對(duì)于鼠標(biāo)當(dāng)前位置拖動(dòng)鼠標(biāo)
pyautogui.dragRel(xOffset, yOffset, duration=num_seconds)
⑤ 調(diào)用click()只會(huì)讓鼠標(biāo)在當(dāng)前位置用左鍵單擊一次,但關(guān)鍵字參數(shù)可以改變這一點(diǎn),button關(guān)鍵字參數(shù)可以'left'是、'middle'或'right'。
pyautogui.click(x=moveToX, y=moveToY, clicks=num_of_clicks, interval=secs_between_clicks,button = 'left')
⑥ 單獨(dú)調(diào)用指定鍵的點(diǎn)擊事件
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ù)控制滾輪將向上滾動(dòng),負(fù)數(shù)控制滾輪將向下滾動(dòng)
pyautogui.scroll(amount_to_scroll, x=moveToX, y=moveToY)
⑧ 單獨(dú)調(diào)用鼠標(biāo)的按下和松開(kāi)事件
pyautogui.mouseDown(x=moveToX, y=moveToY, button='left') pyautogui.mouseUp(x=moveToX, y=moveToY, button='left')
4. 鍵盤控制
① 在鍵盤光標(biāo)處輸入指定文本
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)可以通過(guò)將鍵名稱列表傳遞給hotkey()來(lái)完成:
pyautogui.hotkey('ctrl', 'c') # ctrl-c 復(fù)制
pyautogui.hotkey('ctrl', 'v') # ctrl-v 粘貼④ 單獨(dú)調(diào)用按鈕的點(diǎn)擊事件和松開(kāi)事件:
pyautogui.keyDown(鍵名稱) pyautogui.keyUp(鍵名稱)
5. 消息框函數(shù)
如果您需要暫停程序直到用戶單擊確定,或者想要向用戶顯示一些信息,則可使用消息框函數(shù)。
pyautogui.alert('這將顯示帶有確定按鈕的文本。')
pyautogui.confirm('這將顯示帶有確定和取消按鈕的文本。')
pyautogui.prompt('這樣用戶就可以輸入一個(gè)字符串,然后按確定。')6. 截圖功能
① PyAutoGUI使用Pillow/PIL來(lái)存儲(chǔ)與圖像相關(guān)的數(shù)據(jù)。
pyautogui.screenshot() # 返回Pillow/PIL圖像對(duì)象
pyautogui.screenshot('foo.png') # 返回Pillow/PIL圖像對(duì)象,并將其保存到文件② 返回在當(dāng)前界面找到第一個(gè)圖標(biāo)位置的元組 (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坐標(biāo)。
>>> pyautogui.locateCenterOnScreen('looksLikeThis.png') # 返回中心坐標(biāo) (898,423)
三、進(jìn)階教程
1. 鼠標(biāo)控制
1.1 pyautogui.size()
返回屏幕的分辨率大小,返回類型為元組。
>>> pyautogui.size() (1920, 1080)
1.2 pyautogui.position()
返回鼠標(biāo)光標(biāo)的當(dāng)前位置,返回類型為元組。
>>> pyautogui.position() (187, 567)
1.3 pyautogui.onScreen()
判斷指定位置是否在屏幕內(nèi),返回類型為布爾型。
>>> pyautogui.onScreen(0, 0) True >>> pyautogui.onScreen(0, -1) False >>> pyautogui.onScreen(0, 99999999) False
1.4 pyautogui.move()
移動(dòng)鼠標(biāo)光標(biāo)以當(dāng)前位置為起點(diǎn)移動(dòng)指定距離,如果輸入 None 則為當(dāng)前位置的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.
第三個(gè)參數(shù)可以設(shè)置鼠標(biāo)移動(dòng)到指定位置所花費(fèi)的時(shí)間。
>>> pyautogui.moveTo(100, 200, 2) # moves mouse to X of 100, Y of 200 over 2 seconds
1.5 pyautogui.moveTo()
與move()類似,此函數(shù)可以按照絕對(duì)位置移動(dòng)鼠標(biāo)。
>>> 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()
以相對(duì)位置拖動(dòng)鼠標(biāo),可指定拖動(dòng)時(shí)按住某個(gè)鍵:'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()
以絕對(duì)位置拖動(dòng)鼠標(biāo),可指定拖動(dòng)時(shí)按住某個(gè)鍵:'left', 'middle', 'right'。
1.8 pyautogui.click()
模擬在鼠標(biāo)當(dāng)前位置單擊鼠標(biāo)左鍵。
>>> 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()
模擬雙擊鼠標(biāo)左鍵。
>>> pyautogui.doubleClick() # perform a left-button double click
1.10 pyautogui.tripleClick()
1.11 pyautogui.rightClick()
1.12 pyautogui.mouseDown()
按下鼠標(biāo)
>>> 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()
松開(kāi)鼠標(biāo)
1.14 pyautogui.scroll()
滾動(dòng)鼠標(biāo)滾輪
>>> 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()
水平滾動(dòng)鼠標(biāo)
>>> pyautogui.hscroll(10) # scroll right 10 "clicks" >>> pyautogui.hscroll(-10) # scroll left 10 "clicks"
1.16 pyautogui.vscroll()
垂直滾動(dòng)鼠標(biāo)
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()
松開(kāi)指定鍵
2.6 pyautogui.hold()
保持按住某個(gè)鍵并松開(kāi)
>>> with pyautogui.hold('shift'):
pyautogui.press(['left', 'left', 'left'])2.7 pyautogui.hotkey()
實(shí)現(xiàn)快捷鍵
>>> pyautogui.hotkey('ctrl', 'shift', 'esc')3. 消息框函數(shù)
PyAutoGUI利用PyMsgBox中的消息框函數(shù)提供了一種跨平臺(tái)的純Python方式來(lái)顯示JavaScript樣式的消息框。提供了四個(gè)消息框函數(shù):
3.1 pyautogui.alert()
>>> alert(text='', title='', button='OK')
顯示一個(gè)簡(jiǎn)單的消息框,其中包含文本和一個(gè)確定按鈕。返回單擊的按鈕的文本。
3.2 pyautogui.confirm()
>>> confirm(text='', title='', buttons=['OK', 'Cancel'])
顯示帶有確定和取消按鈕的消息框??梢宰远x按鈕的數(shù)量和文本。返回單擊的按鈕的文本。
3.3 pyautogui.prompt()
>>> prompt(text='', title='' , default='')
顯示帶有文本輸入和確定和取消按鈕的消息框。返回輸入的文本,如果單擊了取消,則返回None。
3.4 pyautogui.password()
>>> password(text='', title='', default='', mask='*')
顯示帶有文本輸入和確定和取消按鈕的消息框。鍵入的字符顯示為*。返回輸入的文本,如果單擊了取消,則返回None。
4. 截圖功能
PyAutoGUI可以截取屏幕截圖,將它們保存到文件中,并在屏幕內(nèi)定位圖像。
例如,如果您有一個(gè)需要單擊的按鈕的小圖像,并且想要在屏幕上找到它,這是很有用的。這些功能由隨PyAutoGUI一起安裝的PyScreeze模塊提供。
4.1 pyautogui.screenshot()
調(diào)用screenshot()將返回一個(gè) Image 對(duì)象(有關(guān)詳細(xì)信息,請(qǐng)參閱 Pillow 或 PIL 模塊文檔)。傳遞文件名字符串會(huì)將屏幕截圖保存到文件中,并將其作為 Image 對(duì)象返回。
>>> import pyautogui
>>> im1 = pyautogui.screenshot()
>>> im2 = pyautogui.screenshot('my_screenshot.png') # 捕獲并保存到本地
>>> im3 = pyautogui.screenshot(region=(0,0, 300, 400)) # 捕獲指定范圍4.2 pyautogui.locateOnScreen()
獲取屏幕坐標(biāo)。返回值是一個(gè) 4 整數(shù)元組:(left, top, width, height)。可以傳遞此元組center()以獲取此區(qū)域中心的 X 和 Y 坐標(biāo)。
4.3 pyautogui.locateCenterOnScreen()
返回在屏幕上找到的第一個(gè)實(shí)例的中心的 (x, y) 坐標(biāo)。
4.4 pyautogui.locateAllOnScreen()
返回一個(gè)生成器,該生成器生成(左、上、寬、高)元組。
4.5 pyautogui.pixel()
獲取屏幕截圖中像素的 RGB 顏色
>>> import pyautogui >>> im = pyautogui.screenshot() >>> im.getpixel((100, 200)) (130, 135, 144)
4.6 pyautogui.pixelMatchesColor()
驗(yàn)證單個(gè)像素是否與給定像素匹配。
>>> import pyautogui >>> pyautogui.pixelMatchesColor(100, 200, (130, 135, 144)) True >>> pyautogui.pixelMatchesColor(100, 200, (0, 0, 0)) False
四、實(shí)例
1. 自動(dòng)點(diǎn)擊網(wǎng)頁(yè)指定圖標(biāo)
參考鏈接:
import pyautogui
import time
while True:
# 本頁(yè)存在指定圖標(biāo)
if pyautogui.locateOnScreen('icon.png'):
time.sleep(0.5) # 等待 0.5 秒
position = pyautogui.center(pyautogui.locateOnScreen('icon.png')) # 尋找圖標(biāo)的中心
pyautogui.click(position) # 點(diǎn)擊
# 本頁(yè)不存在指定圖標(biāo)
else:
pyautogui.scroll(-500) # 滾動(dòng)鼠標(biāo),進(jìn)入下一頁(yè)
2. 獲取鼠標(biāo)當(dāng)前位置
# 案例獲取鼠標(biāo)的位置,方便復(fù)制我們定位的鼠標(biāo)坐標(biāo)點(diǎn)到代碼中
import pyautogui
import time
# 獲取鼠標(biāo)位置
def get_mouse_positon():
time.sleep(5) # 準(zhǔn)備時(shí)間
print('開(kāi)始獲取鼠標(biāo)位置')
try:
for i in range(10):
# Get and print the mouse coordinates.
x, y = pyautogui.position()
positionStr = '鼠標(biāo)坐標(biāo)點(diǎn)(X,Y)為:{},{}'.format(str(x).rjust(4), str(y).rjust(4))
pix = pyautogui.screenshot().getpixel((x, y)) # 獲取鼠標(biāo)所在屏幕點(diǎn)的RGB顏色
positionStr += ' RGB:(' + str(pix[0]).rjust(3) + ',' + str(pix[1]).rjust(3) + ',' + str(pix[2]).rjust(
3) + ')'
print(positionStr)
time.sleep(0.5) # 停頓時(shí)間
except:
print('獲取鼠標(biāo)位置失敗')
if __name__ == "__main__":
get_mouse_positon()
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python程序中使用SQLAlchemy時(shí)出現(xiàn)亂碼的解決方案
這篇文章主要介紹了Python程序中使用SQLAlchemy時(shí)出現(xiàn)亂碼的解決方案,SQLAlchemy是Python常用的操作MySQL數(shù)據(jù)庫(kù)的工具,需要的朋友可以參考下2015-04-04
OpenCV4.1.0+VS2017環(huán)境配置的方法步驟
這篇文章主要介紹了OpenCV4.1.0+VS2017環(huán)境配置的方法步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
django的autoreload機(jī)制實(shí)現(xiàn)
這篇文章主要介紹了django的autoreload機(jī)制實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
python如何每天在指定時(shí)間段運(yùn)行程序及關(guān)閉程序
這篇文章主要介紹了python如何每天在指定時(shí)間段運(yùn)行程序及關(guān)閉程序問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。2023-04-04
matplotlib bar()實(shí)現(xiàn)多組數(shù)據(jù)并列柱狀圖通用簡(jiǎn)便創(chuàng)建方法
這篇文章主要介紹了matplotlib bar()實(shí)現(xiàn)多組數(shù)據(jù)并列柱狀圖通用簡(jiǎn)便創(chuàng)建方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
python爬蟲(chóng)之selenium庫(kù)的安裝及使用教程
今天帶大家來(lái)學(xué)習(xí)怎么安裝使用selenium庫(kù),文中有非常詳細(xì)的圖文介紹,對(duì)正在學(xué)習(xí)python爬蟲(chóng)的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05
Python實(shí)現(xiàn)word2Vec model過(guò)程解析
這篇文章主要介紹了Python實(shí)現(xiàn)word2Vec model過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12

