PyAutoGUI——讓所有GUI都自動化


2015-08-17:輸入中文bug沒有解決,目前的解決方案是Python 2.X環境下安裝pyperclip和pyautogui,用復制粘貼來實現。

In [ ]:
import pyperclip import pyautogui # PyAutoGUI中文輸入需要用粘貼實現 # Python 2版本的pyperclip提供中文復制 def paste(foo): pyperclip.copy(foo) pyautogui.hotkey('ctrl', 'v') foo = u'學而時習之' # 移動到文本框 pyautogui.click(130,30) paste(foo) 
 

1.簡介

 

1.1 目的

 

PyAutoGUI是一個純Python的GUI自動化工具,其目的是可以用程序自動控制鼠標和鍵盤操作,多平台支持(Windows,OS X,Linux)。可以用pip安裝,Github上有源代碼

下面的代碼讓鼠標移到屏幕中央。

In [ ]:
import pyautogui screenWidth, screenHeight = pyautogui.size() pyautogui.moveTo(screenWidth / 2, screenHeight / 2) 
 

PyAutoGUI可以模擬鼠標的移動、點擊、拖拽,鍵盤按鍵輸入、按住操作,以及鼠標+鍵盤的熱鍵同時按住等操作,可以說手能動的都可以。

 

1.2 例子

In [ ]:
import pyautogui screenWidth, screenHeight = pyautogui.size() currentMouseX, currentMouseY = pyautogui.position() pyautogui.moveTo(100, 150) pyautogui.click() # 鼠標向下移動10像素 pyautogui.moveRel(None, 10) pyautogui.doubleClick() # 用緩動/漸變函數讓鼠標2秒后移動到(500,500)位置 # use tweening/easing function to move mouse over 2 seconds. pyautogui.moveTo(1800, 500, duration=2, tween=pyautogui.easeInOutQuad) # 在每次輸入之間暫停0.25秒 pyautogui.typewrite('Hello world!', interval=0.25) pyautogui.press('esc') pyautogui.keyDown('shift') pyautogui.press(['left', 'left', 'left', 'left', 'left', 'left']) pyautogui.keyUp('shift') pyautogui.hotkey('ctrl', 'c') 
In [ ]:
distance = 200 while distance > 0: pyautogui.dragRel(distance, 0, duration=0.5) # 向右 distance -= 5 pyautogui.dragRel(0, distance, duration=0.5) # 向下 pyautogui.draIn gRel(-distance, 0, duration=0.5) # 向左 distance -= 5 pyautogui.dragRel(0, -distance, duration=0.5) # 向上 
 

1.4 保護措施(Fail-Safes)

 

就像《魔法師的學徒》(Sorcerer’s Apprentice)會擔水的掃帚,可以擔水,卻無力阻止水漫浴室。你的程序也可能會失控(即使是按照你的意思執行的),那時就需要中斷。如果鼠標還在自動操作,就很難在程序窗口關閉它。

為了能夠及時中斷,PyAutoGUI提供了一個保護措施。當pyautogui.FAILSAFE = True時,如果把鼠標光標在屏幕左上角,PyAutoGUI函數就會產生pyautogui.FailSafeException異常。如果失控了,需要中斷PyAutoGUI函數,就把鼠標光標在屏幕左上角。要禁用這個特性,就把FAILSAFE設置成False

In [ ]:
import pyautogui pyautogui.FAILSAFE = False 
 

通過把pyautogui.PAUSE設置成floatint時間(秒),可以為所有的PyAutoGUI函數增加延遲。默認延遲時間是0.1秒。在函數循環執行的時候,這樣做可以讓PyAutoGUI運行的慢一點,非常有用。例如:

In [ ]:
import pyautogui pyautogui.PAUSE = 2.5 pyautogui.moveTo(100,100); pyautogui.click() 
 

所有的PyAutoGUI函數在延遲完成前都處於阻塞狀態(block)。(未來計划增加一個可選的非阻塞模式來調用函數。)

建議PAUSEFAILSAFE一起使用。

 

2 安裝與依賴

PyAutoGUI支持Python 2.x和Python 3.x

  • Windows:PyAutoGUI沒有任何依賴,因為它用Python的ctypes模塊所以不需要pywin32
    pip3 install pyautogui
  • OS X:PyAutoGUI需要PyObjC運行AppKit和Quartz模塊。這個模塊在PyPI上的按住順序是pyobjc-corepyobjc
    sudo pip3 install pyobjc-core
    sudo pip3 install pyobjc
    sudo pip3 install pyautogui
  • Linux:PyAutoGUI需要python-xlib(Python 2)、python3-Xlib(Python 3)
    sudo pip3 install python3-xlib
    sudo apt-get scrot
    sudo apt-get install python-tk
    sudo apt-get install python3-dev
    sudo pip3 install pyautogui
 

3.速查表(小抄,Cheat Sheet)

 

3.1 常用函數

In [ ]:
import pyautogui # 當前鼠標的坐標 pyautogui.position() 
Out[ ]:
(123, 372)
In [ ]:
#  當前屏幕的分辨率(寬度和高度)
pyautogui.size() 
Out[ ]:
(1920, 1080)
In [ ]:
#  (x,y)是否在屏幕上
x, y = 122, 244 pyautogui.onScreen(x, y) 
Out[ ]:
True
 

3.2 保護措施

 

PyAutoGUI函數增加延遲為2.5秒:

In [ ]:
import pyautogui pyautogui.PAUSE = 2.5 
 

當pyautogui.FAILSAFE = True時,如果把鼠標光標在屏幕左上角,PyAutoGUI函數就會產生pyautogui.FailSafeException異常。

In [ ]:
import pyautogui pyautogui.FAILSAFE = True 
 

3.3 鼠標函數

 

坐標系的原點是左上角。X軸(水平)坐標向右增大,Y軸(豎直)坐標向下增大。

In [ ]:
num_seconds = 1.2 # 用num_seconds秒的時間把光標移動到(x, y)位置 pyautogui.moveTo(x, y, duration=num_seconds) # 用num_seconds秒的時間把光標的X軸(水平)坐標移動xOffset, # Y軸(豎直)坐標向下移動yOffset。 xOffset, yOffset = 50, 100 pyautogui.moveRel(xOffset, yOffset, duration=num_seconds) 
 

click()函數就是讓鼠標點擊,默認是單擊左鍵,參數可以設置:

In [ ]:
pyautogui.click(x=moveToX, y=moveToY, clicks=num_of_clicks, interval=secs_between_clicks, button='left') 
 

其中,button屬性可以設置成leftmiddleright

所有的點擊都可以用這個函數,不過下面的函數可讀性更好:

In [ ]:
pyautogui.rightClick(x=moveToX, y=moveToY) pyautogui.middleClick(x=moveToX, y=moveToY) pyautogui.doubleClick(x=moveToX, y=moveToY) pyautogui.tripleClick(x=moveToX, y=moveToY) 
 

scroll函數控制鼠標滾輪的滾動,amount_to_scroll參數表示滾動的格數。正數則頁面向上滾動,負數則向下滾動:

In [ ]:
pyautogui.scroll(clicks=amount_to_scroll, x=moveToX, y=moveToY) 
 

每個按鍵按下和松開兩個事件可以分開處理:

In [ ]:
pyautogui.mouseDown(x=moveToX, y=moveToY, button='left') pyautogui.mouseUp(x=moveToX, y=moveToY, button='left') 
 

3.4 鍵盤函數

 

鍵盤上可以按的鍵都可以調用:

In [ ]:
#  每次鍵入的時間間隔
secs_between_keys = 0.1 pyautogui.typewrite('Hello world!\n', interval=secs_between_keys) 
 

多個鍵也可以:

In [ ]:
pyautogui.typewrite(['a', 'b', 'c', 'left', 'backspace', 'enter', 'f1'], interval=secs_between_keys) 
 

按鍵名稱列表:

In [ ]:
pyautogui.KEYBOARD_KEYS[:10] 
Out[ ]:
['\t', '\n', '\r', ' ', '!', '"', '#', '$', '%', '&']
 

鍵盤的一些熱鍵像Ctrl-SCtrl-Shift-1都可以用hotkey()函數來實現:

In [ ]:
pyautogui.hotkey('ctrl', 'a') # 全選 pyautogui.hotkey('ctrl', 'c') # 復制 pyautogui.hotkey('ctrl', 'v') # 粘貼 
 

每個按鍵的按下和松開也可以單獨調用:

In [ ]:
pyautogui.keyDown(key_name) pyautogui.keyUp(key_name) 
 

3.5 消息彈窗函數

 

如果你需要消息彈窗,通過單擊OK暫停程序,或者向用戶顯示一些信息,消息彈窗函數就會有類似JavaScript的功能:

In [ ]:
pyautogui.alert('這個消息彈窗是文字+OK按鈕') pyautogui.confirm('這個消息彈窗是文字+OK+Cancel按鈕') pyautogui.prompt('這個消息彈窗是讓用戶輸入字符串,單擊OK') 
Out[ ]:
''
 

prompt()函數中,如果用戶什么都不輸入,就會返回None

 

3.6 截屏函數

 

PyAutoGUI用Pillow/PIL庫實現圖片相關的識別和操作。

在Linux里面,你必須執行sudo apt-get install scrot來使用截屏特性。

In [ ]:
#  返回一個Pillow/PIL的Image對象
pyautogui.screenshot() pyautogui.screenshot('foo.png') 
 

如果你有一個圖片文件想在上面做點擊操作,你可以用locateOnScreen()函數來定位。

In [ ]:
#  返回(最左x坐標,最頂y坐標,寬度,高度)
pyautogui.locateOnScreen('pyautogui/looks.png') 
Out[ ]:
(0, 1040, 48, 40)
 

locateAllOnScreen()函數會尋找所有相似圖片,返回一個生成器:

In [ ]:
for i in pyautogui.locateAllOnScreen('pyautogui/looks.png'): print(i) 
 
(0, 1040, 48, 40)
In [ ]:
list(pyautogui.locateAllOnScreen('pyautogui/looks.png')) 
Out[ ]:
[(0, 1040, 48, 40)]
 

locateCenterOnScreen()函數會返回圖片在屏幕上的中心XY軸坐標值:

In [ ]:
pyautogui.locateCenterOnScreen('pyautogui/looks.png') 
Out[ ]:
(24, 1060)
 

如果沒找到圖片會返回None

定位比較慢,一般得用1~2秒

 

4 常用函數

 
  • position():返回整數元組(x, y),分別表示鼠標光標所在位置的XY軸坐標
  • size():返回顯示器的尺寸整數元組(x, y)。未來將加入多屏支持
 

5 鼠標控制函數

 

5.1 屏幕與鼠標位置

 

屏幕位置使用X和Y軸的笛卡爾坐標系。原點(0,0)在左上角,分別向右、向下增大。

如果屏幕像素是1920×10801920×1080,那么右下角的坐標是(1919, 1079)

分辨率大小可以通過size()函數返回整數元組。光標的位置用position()返回。例如:

In [ ]:
pyautogui.size() 
Out[ ]:
(1920, 1080)
In [ ]:
pyautogui.position() 
Out[ ]:
(272, 688)
 

下面是Python 3版本的光標位置記錄程序:

In [ ]:
# ! python 3
import pyautogui print('Press Ctrl-C to quit') try: while True: x, y = pyautogui.position() positionStr = 'X: {} Y: {}'.format(*[str(x).rjust(4) for x in [x, y]]) print(positionStr, end='') print('\b' * len(positionStr), end='', flush=True) except KeyboardInterrupt: print('\n') 
 

Python 2版本是:

In [ ]:
# ! python
import pyautogui, sys print('Press Ctrl-C to quit.') try: while True: x, y = pyautogui.position() positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) print positionStr, print '\b' * (len(positionStr) + 2), sys.stdout.flush() except KeyboardInterrupt: print '\n' 
 

要檢查XY坐標是否在屏幕上,需要用onScreen()函數來檢驗,如果在屏幕上返回True

In [ ]:
import pyautogui pyautogui.onScreen(0, 0) 
Out[ ]:
True
In [ ]:
pyautogui.onScreen(0, -1) 
Out[ ]:
False
In [ ]:
pyautogui.onScreen(0, 2080) 
Out[ ]:
False
In [ ]:
pyautogui.onScreen(1920, 1080) 
Out[ ]:
False
In [ ]:
pyautogui.onScreen(1919, 1079) 
Out[ ]:
True
 

5.2 鼠標行為

 

moveTo()函數會把鼠標光標移動到指定的XY軸坐標處。如果傳入None值,則表示使用當前光標的對象軸坐標值。

In [ ]:
pyautogui.moveTo(100, 200) # 光標移動到(100, 200)位置 pyautogui.moveTo(None, 500) # 光標移動到(100, 500)位置 pyautogui.moveTo(600, None) # 光標移動到(600, 500)位置 
 

一般鼠標光標都是瞬間移動到指定的位置,如果你想讓鼠標移動的慢點,可以設置持續時間:

In [ ]:
pyautogui.moveTo(100, 200, duration=2) # 用2秒把光標移動到(100, 200)位置 
 

默認的持續時間pyautogui.MINIMUM_DURATION是0.1秒,如果你設置的時間比默認值還短,那么就會瞬間執行。

如果你想讓光標以當前位置為原點,進行相對移動,就用pyautogui.moveRel()函數。例如:

In [ ]:
pyautogui.moveTo(100, 200) #把光標移動到(100, 200)位置 pyautogui.moveRel(0, 50) #向下移動50 pyautogui.moveRel(30, 0, 2) #向右移動30 pyautogui.moveRel(30, None) #向右移動30 
 

5.3 鼠標拖拽

 

PyAutoGUI的dragTo()dragRel()函數與moveTo()moveRel()函數類似。另外,他們有一個button參數可以設置成leftmiddleright三個鍵。例如:

In [ ]:
#  按住鼠標左鍵,把鼠標拖拽到(100, 200)位置
pyautogui.dragTo(100, 200, button='left') # 按住鼠標左鍵,用2秒鍾把鼠標拖拽到(300, 400)位置 pyautogui.dragTo(300, 400, 2, button='left') # 按住鼠標右鍵,用2秒鍾把鼠標拖拽到(30,0)位置 pyautogui.dragTo(30, 0, 2, button='right') 
 

5.4 緩動/漸變(Tween / Easing)函數

 

緩動/漸變函數的作用是讓光標的移動更炫。如果你不需要用到的話,你可以忽略這些。

緩動/漸變函數可以改變光標移動過程的速度和方向。通常鼠標是勻速直線運動,這就是線性緩動/漸變函數。PyAutoGUI有30種緩動/漸變函數,可以通過pyautogui.ease*?查看。其中,pyautogui.easeInQuad()函數可以用於moveTo()moveRel()dragTo()dragRel()函數,光標移動呈現先慢后快的效果,整個過程的時間還是和原來一樣。而pyautogui.easeOutQuad函數的效果相反:光標開始移動很快,然后慢慢減速。pyautogui.easeOutElastic是彈簧效果,首先越過終點,然后再反彈回來。例如:

In [ ]:
#  開始很慢,不斷加速
pyautogui.moveTo(100, 100, 2, pyautogui.easeInQuad) # 開始很快,不斷減速 pyautogui.moveTo(100, 100, 2, pyautogui.easeOutQuad) # 開始和結束都快,中間比較慢 pyautogui.moveTo(100, 100, 2, pyautogui.easeInOutQuad) # 一步一徘徊前進 pyautogui.moveTo(100, 100, 2, pyautogui.easeInBounce) # 徘徊幅度更大,甚至超過起點和終點 pyautogui.moveTo(100, 100, 2, pyautogui.easeInElastic) 
 

這些效果函數是模仿Al Sweigart的PyTweening模塊,可以直接使用,不需要額外安裝。

如果你想創建自己的效果,也可以定義一個函數,其參數是(0.0,1.0),表示起點和終點,返回值是介於[0.0,1.0]之間的數。

 

5.5 鼠標單擊

 

click()函數模擬單擊鼠標左鍵一次的行為。例如:

In [ ]:
pyautogui.click() 
 

如果單機之前要先移動,可以把目標的XY坐標值傳入函數:

In [ ]:
#  先移動到(100, 200)再單擊
pyautogui.click(x=100, y=200, duration=2) 
 

可以通過button參數設置leftmiddleright三個鍵。例如:

In [ ]:
pyautogui.click(button='right') 
 

要做多次單擊可以設置clicks參數,還有interval參數可以設置每次單擊之間的時間間隔。例如:

In [ ]:
#  雙擊左鍵
pyautogui.click(clicks=2) # 兩次單擊之間停留0.25秒 pyautogui.click(clicks=2, interval=0.25) # 三擊右鍵 pyautogui.click(button='right', clicks=2, interval=0.25) 
 

為了操作方便,PyAutoGUI提供了doubleClick()tripleClick()rightClick()來實現雙擊、三擊和右擊操作。

 

5.6 鼠標按下和松開函數

 

mouseDown()mouseUp()函數可以實現鼠標按下和鼠標松開的操作。兩者參數相同,有xybutton。例如:

In [ ]:
#  鼠標左鍵按下再松開
pyautogui.mouseDown(); pyautogui.mouseUp() # 按下鼠標右鍵 pyautogui.mouseDown(button='right') # 移動到(100, 200)位置,然后松開鼠標右鍵 pyautogui.mouseUp(button='right', x=100, y=200) 
 

5.7 滾輪滾動函數

 

鼠標滾輪滾動可以用scroll()函數和clicks次數參數來模擬。不同平台上的clicks次數不太一樣。還有xy參數可以在滾動之前定位到(x, y)位置。例如:

In [ ]:
#  向上滾動10格
pyautogui.scroll(10) # 向下滾動10格 pyautogui.scroll(-10) # 移動到(100, 100)位置再向上滾動10格 pyautogui.scroll(10, x=100, y=100) 
 

在OS X和Linux平台上,PyAutoGUI還可以用hscroll()實現水平滾動。例如:

In [ ]:
#  向右滾動10格
pyautogui.hscroll(10) # 向左滾動10格 pyautogui.hscroll(-10) 
 

scroll()函數是vscroll()的一個包裝(wrapper),執行豎直滾動。

 

6 鍵盤控制函數

 

6.1 typewrite()輸入函數

 

鍵盤控制的主要函數就是typewrite()。這個函數可以實現字符輸入。要在兩次輸入間增加時間間隔,可以用interval參數。例如:

In [ ]:
#  輸入Hello world!
pyautogui.typewrite('Hello world!') # 每次輸入間隔0.25秒,輸入Hello world! pyautogui.typewrite('Hello world!', interval=0.25) 
 

typewrite()函數只能用於單個字符鍵,不能按SHITF和F1這些功能鍵。

 

6.2 press()keyDown()keyUp()函數

 

要按那些功能鍵,可以用press()函數把pyautogui.KEYBOARD_KEYS里面按鍵對應的字符串輸入進去。例如:

In [ ]:
#  ENTER鍵
pyautogui.press('enter') # F1鍵 pyautogui.press('f1') # 左方向鍵 pyautogui.press('left') 
 

press()函數其實是keyDown()keyUp()函數的包裝,模擬的按下然后松開兩個動作。這兩個函數可以單獨調用。例如,按下shift鍵的同時按3次左方向鍵:

In [ ]:
#  按下`shift`鍵
pyautogui.keyDown('shift') pyautogui.press('left') pyautogui.press('left') pyautogui.press('left') # 松開`shift`鍵 pyautogui.keyUp('shift') 
 

typewrite()函數一樣,可以用數組把一組鍵傳入press()。例如:

In [ ]:
pyautogui.press(['left', 'left', 'left']) 
 

6.3 hotkey()函數

 

為了更高效的輸入熱鍵,PyAutoGUI提供了hotkey()函數來綁定若干按鍵:

In [ ]:
pyautogui.hotkey('ctrl', 'shift', 'ese') 
 

等價於:

In [ ]:
pyautogui.keyDown('ctrl') pyautogui.keyDown('shift') pyautogui.keyDown('esc') pyautogui.keyUp('esc') pyautogui.keyUp('shift') pyautogui.keyUp('ctrl') 
 

6.4 KEYBOARD_KEYS

 

下面就是press()keyDown()keyUp()hotkey()函數可以輸入的按鍵名稱:

In [ ]:
print(pyautogui.KEYBOARD_KEYS) 
 
['\t', '\n', '\r', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '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', '{', '|', '}', '~', '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', 'f1', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f2', 'f20', 'f21', 'f22', 'f23', 'f24', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'final', 'fn', 'hanguel', 'hangul', 'hanja', 'help', 'home', 'insert', 'junja', 'kana', 'kanji', 'launchapp1', 'launchapp2', 'launchmail', 'launchmediaselect', 'left', 'modechange', 'multiply', 'nexttrack', 'nonconvert', 'num0', 'num1', 'num2', 'num3', 'num4', 'num5', 'num6', 'num7', 'num8', 'num9', 'numlock', 'pagedown', 'pageup', 'pause', 'pgdn', 'pgup', 'playpause', 'prevtrack', 'print', 'printscreen', 'prntscrn', 'prtsc', 'prtscr', 'return', 'right', 'scrolllock', 'select', 'separator', 'shift', 'shiftleft', 'shiftright', 'sleep', 'stop', 'subtract', 'tab', 'up', 'volumedown', 'volumemute', 'volumeup', 'win', 'winleft', 'winright', 'yen', 'command', 'option', 'optionleft', 'optionright']
 

7 消息彈窗函數

 

PyAutoGUI通過Tkinter實現了4種純Python的消息彈窗函數,和JavaScript類似。

 

7.1 alert()函數

In [ ]:
pyautogui.alert(text='', title='', button='OK') 
Out[ ]:
'OK'
 

顯示一個簡單的帶文字和OK按鈕的消息彈窗。用戶點擊后返回button的文字。

 

7.2 The confirm() Function

In [ ]:
#  OK和Cancel按鈕的消息彈窗
pyautogui.confirm(text='', title='', buttons=['OK', 'Cancel']) # 10個按鍵0-9的消息彈窗 pyautogui.confirm(text='', title='', buttons=range(10)) 
Out[ ]:
'0'
 

顯示一個簡單的帶文字、OK和Cancel按鈕的消息彈窗,用戶點擊后返回被點擊button的文字,支持自定義數字、文字的列表。

 

7.3 The prompt() Function

In [ ]:
pyautogui.prompt(text='', title='' , default='') 
 

可以輸入的消息彈窗,帶OK和Cancel按鈕。用戶點擊OK按鈕返回輸入的文字,點擊Cancel按鈕返回None

 

7.4 The password() Function

In [ ]:
pyautogui.password(text='', title='', default='', mask='*') 
 

樣式同prompt(),用於輸入密碼,消息用*表示。帶OK和Cancel按鈕。用戶點擊OK按鈕返回輸入的文字,點擊Cancel按鈕返回None

 

8 截屏函數

 

PyAutoGUI可以截屏並保存為圖片文件,然后定位這些截屏在屏幕上的位置。與sikuli類似,把屏幕上的按鍵截取下來,然后定位,就可以執行點擊等操作了。

截屏功能需要安裝Pillow模塊。OS X用screencapture命令,是系統自帶的。Linux用戶用scrot命令,可以通過sudo apt-get install scrot安裝。

 

8.1 Ubuntu注意事項

 

由於Ubuntu上安裝Pillow時缺少PNG和JPEG依賴,所以安裝比較復雜,具體可以看Ubuntu論壇。不過用miniconda可以解決這些問題,如果Ubuntu或Mint上安裝了miniconda,可以直接conda install pillow來安裝。

 

8.2 screenshot()函數

 

screenshot()函數會返回Image對象(參考Pillow或PIL模塊文檔),也可以設置文件名:

In [ ]:
import pyautogui im1 = pyautogui.screenshot() im2 = pyautogui.screenshot('my_screenshot.png') 
 

在一個1920×10801920×1080的屏幕上,screenshot()函數要消耗100微秒——不快也不慢。

如果你不需要截取整個屏幕,還有一個可選的region參數。你可以把截取區域的左上角XY坐標值和寬度、高度傳入截取。

In [ ]:
im = pyautogui.screenshot(region=(0, 0, 300 ,400)) 
 

8.3 定位函數

 

可以定位截圖在屏幕上的坐標位置。比如,你需要在計算器里輸入:

如果你不知道按鈕的位置,就不能用moveTo()定位和click()點擊。而且每次計算器的位置可能會變化,這時即使有來坐標也不好用了。但是如果你有要點擊按鈕的截圖,比如數字7

你可以調用pyautogui.locateOnScreen('calc7key.png')函數來獲得7的屏幕坐標。返回的是一個元組(top, left, width, height)。這個元組可以用pyautogui.center()函數來獲取截圖屏幕的中心坐標。如果截圖沒找到,pyautogui.locateOnScreen()函數返回None

In [ ]:
import pyautogui button7location = pyautogui.locateOnScreen('pyautogui/calc7key.png') button7location 
Out[ ]:
(1226, 546, 29, 28)
In [ ]:
button7x, button7y = pyautogui.center(button7location) button7x, button7y 
Out[ ]:
(1240, 560)
In [ ]:
pyautogui.click(button7x, button7y) 
 

locateCenterOnScreen()等價於上面的前兩布操作,直接獲得截屏屏幕中心坐標:

In [ ]:
import pyautogui x, y = pyautogui.locateCenterOnScreen('pyautogui/calc7key.png') pyautogui.click(x, y) 
 

1920×10801920×1080的屏幕上,定位函數需要1~2秒時間。對視頻游戲(LOL、DOTA)來說就太慢了,但是上班干活還是綽綽有余。

還是幾個定位函數。都是從左上角原點開始向右向下搜索截圖位置:

  • locateOnScreen(image, grayscale=False):返回找到的第一個截圖Image對象在屏幕上的坐標(left, top, width, height),如果沒找到返回None
  • locateCenterOnScreen(image, grayscale=False):返回找到的第一個截圖Image對象在屏幕上的中心坐標(x, y),如果沒找到返回None
  • locateAllOnScreen(image, grayscale=False):返回找到的所有相同截圖Image對象在屏幕上的坐標(left, top, width, height)的生成器
  • locate(needleImage, haystackImage, grayscale=False):返回找到的第一個截圖Image對象在haystackImage里面的坐標(left, top, width, height),如果沒找到返回None
  • locateAll(needleImage, haystackImage, grayscale=False):返回找到的所有相同截圖Image對象在haystackImage里面的坐標(left, top, width, height)的生成器

兩個locateAll*函數都可以用for循環和list()輸出:

In [ ]:
for pos in pyautogui.locateAllOnScreen('pyautogui/calc7key.png'): print(pos) 
 
(1227, 546, 29, 28)
In [ ]:
list(pyautogui.locateAllOnScreen('pyautogui/calc7key.png')) 
Out[ ]:
[(1227, 546, 29, 28)]
 

8.3.1 灰度值匹配

 

可以把grayscale參數設置為True來加速定位(大約提升30%),默認為False。這種去色(desaturate)方法可以加速定位,但是也可能導致假陽性(false-positive)匹配:

In [ ]:
import pyautogui button7location = pyautogui.locateOnScreen('pyautogui/calc7key.png', grayscale=True) button7location 
Out[ ]:
(1227, 546, 29, 28)
 

8.3.2 像素匹配

 

要獲取截屏某個位置的RGB像素值,可以用Image對象的getpixel()方法:

In [ ]:
import pyautogui im = pyautogui.screenshot() im.getpixel((100, 200)) 
Out[ ]:
(255, 255, 255)
 

也可以用PyAutoGUI的pixel()函數,是之前調用的包裝:

In [ ]:
pyautogui.pixel(100, 200) 
Out[ ]:
(255, 255, 255)
 

如果你只是要檢驗一下指定位置的像素值,可以用pixelMatchesColor()函數,把X、Y和RGB元組值穿入即可:

In [ ]:
pyautogui.pixelMatchesColor(100, 200, (255, 255, 255)) 
Out[ ]:
True
In [ ]:
pyautogui.pixelMatchesColor(100, 200, (255, 255, 245)) 
Out[ ]:
False
 

tolerance參數可以指定紅、綠、藍3種顏色誤差范圍:

In [ ]:
pyautogui.pixelMatchesColor(100, 200, (255, 255, 245), tolerance=10) 
Out[ ]:
True
In [ ]:
pyautogui.pixelMatchesColor(100, 200, (248, 250, 245), tolerance=10) 
Out[ ]:
True
In [ ]:
pyautogui.pixelMatchesColor(100, 200, (205, 255, 245), tolerance=10) 
Out[ ]:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM