本篇 ShengYu 將介紹如何用 Python 搭配 pyautogui 模組來模擬鍵盤、模擬滑鼠,Python 如何模擬鍵盤按下按鍵與模擬滑鼠移動滑鼠與點擊,將在以下教學內容解釋。
如果遇到 ImportError: No module named ‘pyautogui’ 這錯誤訊息就是需要安裝 pyautogui,參考這篇安裝吧!
模擬鍵盤
按下按鍵1
2import pyautogui
'a') # 按 a pyautogui.press(
常用的一些按鍵整理如下表:
用法 | 說明 |
---|---|
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 | (0,0) X 增加 --> |
取得螢幕解析度
1 | import pyautogui |
取得滑鼠當前的座標位置
1 | import pyautogui |
移動滑鼠到絕對位置
語法:moveTo(width, height, duration)
移動到(300, 200)絕對位置
1 | import pyautogui |
移動滑鼠到相對位置
語法:moeRel(width, height, duration)
移到相對位置,以當前滑鼠位置為基準點
1 | import pyautogui |
滑鼠拖曳
1 | 100, 200, button='left') # drag mouse to (100, 200) while holding down left mouse button pyautogui.dragTo( |
滑鼠點擊
語法:click(width, height, button)
1 | button = 'left', 'middle', 'right'。 |
更多滑鼠資訊可參考 https://pyautogui.readthedocs.io/en/latest/mouse.html
其他
暫停幾秒鐘
1 | pyautogui.PAUSE = 1.5 |
Fail-Safes (預設false)
當滑鼠一道螢幕左上角時,觸發 pyautogui 的FailSafeException 異常
1 | pyautogui.FAILSAFE = True # enables the fail-safe |
詳情請看https://pyautogui.readthedocs.io/en/latest/introduction.html#fail-safes
另外 pyautogui 還有 Message Box 和 Screenshot 改天再研究吧!
對 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 模組