Python PyAutoGUI 使用教學

本篇 ShengYu 將介紹如何用 Python 搭配 pyautogui 模組來模擬鍵盤、模擬滑鼠,Python 如何模擬鍵盤按下按鍵與模擬滑鼠移動滑鼠與點擊,將在以下教學內容解釋。

如果遇到 ImportError: No module named ‘pyautogui’ 這錯誤訊息就是需要安裝 pyautogui,參考這篇安裝吧!

模擬鍵盤

按下按鍵

1
2
>>> import pyautogui
>>> pyautogui.press('a') # 按 a

常用的一些按鍵整理如下表:

用法 說明
press(‘a’) a
press(‘enter’) 回車鍵
press(‘esc’) Esc
press(‘space’) space 空白鍵
press(‘backspace’) 返回鍵
press(‘up’)
press(‘down’)
press(‘left’)
press(‘right’)
press(‘pgup’) Page Up
press(‘pgdn’) Page Down
press(‘playpause’) 播放/暫停
press(‘volumeup’) 大聲
press(‘volumedown’) 小聲
press(‘volumemute’) 靜音
press(‘printscreen’) Print Screen
press(‘ctrl’) Ctrl
press(‘shift’) Shift
press(‘alt’) Alt
press(‘option’) Option

更多按鍵資訊可參考
https://pyautogui.readthedocs.io/en/latest/keyboard.html

模擬滑鼠

這邊需要解釋一下螢幕上的座標軸,這樣接下來才清楚滑鼠要往哪邊移動。

以下範例為1920 x 1080 的螢幕解析度示意。

1
2
3
4
5
6
7
8
9
(0,0)       X 增加 -->
+---------------------------+
| | Y 增加
| | |
| 1920 x 1080 screen | |
| | V
| |
| |
+---------------------------+ (1919, 1079)

取得螢幕解析度

1
2
3
>>> import pyautogui
>>> width, height = pyautogui.size()
(1920, 1080)

取得滑鼠當前的座標位置

1
2
3
>>> import pyautogui
>>> pyautogui.position()
(300, 200)

移動滑鼠到絕對位置
語法:moveTo(width, height, duration)
移動到(300, 200)絕對位置

1
2
3
4
5
>>> import pyautogui
>>> pyautogui.moveTo(300, 200) # 移動到(300, 200)
>>> pyautogui.moveTo(None, 400) # 移動到(300, 400)
>>> pyautogui.moveTo(500, None) # 移動到(500, 200)
>>> pyautogui.moveTo(300, 200, duration = 1.5) # 花1.5秒移動到(300, 200)

移動滑鼠到相對位置

語法:moeRel(width, height, duration)
移到相對位置,以當前滑鼠位置為基準點

1
2
3
import pyautogui
pyautogui.moveRel(0, 100)
pyautogui.moveRel(-100, 0)

滑鼠拖曳

1
2
3
>>> pyautogui.dragTo(100, 200, button='left')     # drag mouse to (100, 200) while holding down left mouse button
>>> pyautogui.dragTo(300, 400, 2, button='left') # drag mouse to (300, 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

滑鼠點擊
語法:click(width, height, button)

1
2
3
4
5
button = 'left', 'middle', 'right'

pyautogui.click() #在當前位置點擊(預設左鍵)
pyautogui.click(width, height) #在(width, height)點擊滑鼠(預設左鍵)
pyautogui.click(width, height, button='left') #點擊滑鼠左鍵

更多滑鼠資訊可參考 https://pyautogui.readthedocs.io/en/latest/mouse.html

其他

暫停幾秒鐘

1
pyautogui.PAUSE = 1.5

Fail-Safes (預設false)
當滑鼠一道螢幕左上角時,觸發 pyautogui 的FailSafeException 異常

1
2
pyautogui.FAILSAFE = True # enables the fail-safe
pyautogui.FAILSAFE = False # disables the fail-safe

詳情請看https://pyautogui.readthedocs.io/en/latest/introduction.html#fail-safes

另外 pyautogui 還有 Message BoxScreenshot 改天再研究吧!
對 Python 自動化有興趣可以參考《Python 自動化的樂趣》這本書中的自動化專題實作章節。

參考
PyAutoGUI : 使用Python控制電腦 - Yanwei Liu - Medium
https://medium.com/@yanweiliu/662cc3b18b80
Python学习笔记——用GUI自动化控制键盘和鼠标 - 简书
https://www.jianshu.com/p/41463c82ec8f
python pyautogui 簡介
https://xiang1023.blogspot.com/2017/09/python-pyautogui.html

其它相關文章推薦
Python 安裝 PyAutoGUI 模組