Date: 2025.01.15 20:54:01 author: lijianzhan
PyAutoGUI是一個功能強大的Python庫,它允許我們用于通過編程控制鼠標和鍵盤,實現自動化任務。它可以模擬用戶的輸入操作,例如點擊、拖動、輸入文本等,適用于 GUI 自動化、測試腳本、游戲自動化等場景。
- PyAutoGUI安裝
要開始使用PyAutoGUI,首先你需要通過pip命令進行安裝:
pip install pyautogui
注意:
PyAutoGUI 依賴于 Pillow 庫(用于圖像處理),安裝時會自動安裝。
在 Linux 系統上,可能需要安裝額外的依賴庫(如 scrot 或 mss)以支持截圖功能。
- 控制鼠標操作
import pyautogui
#獲取屏幕分辨率
screen_width, screen_height = pyautogui.size()
print(f"屏幕分辨率: {screen_width}x{screen_height}")#移動鼠標
pyautogui.moveTo(100, 200) # 將鼠標移動到 (100, 200) 位置
pyautogui.move(50, 0) # 將鼠標向右移動 50 像素#點擊鼠標
pyautogui.click() # 在當前鼠標位置點擊左鍵
pyautogui.click(100, 200) # 在 (100, 200) 位置點擊左鍵
pyautogui.rightClick() # 右鍵點擊
pyautogui.doubleClick() # 雙擊左鍵#拖動鼠標
pyautogui.dragTo(300, 400) # 拖動鼠標到 (300, 400)
pyautogui.drag(0, 100) # 向下拖動 100 像素#獲取鼠標位置
x, y = pyautogui.position()
print(f"當前鼠標位置: ({x}, {y})")
- 控制鍵盤
#輸入文本
pyautogui.write("Hello, PyAutoGUI!") # 輸入文本#按下和釋放按鍵
pyautogui.keyDown('shift') # 按下 Shift 鍵
pyautogui.press('a') # 按下并釋放 A 鍵
pyautogui.keyUp('shift') # 釋放 Shift 鍵#快捷鍵
pyautogui.hotkey('ctrl', 'c') # 模擬按下 Ctrl + C
- 截圖與圖像識別
#截圖
screenshot = pyautogui.screenshot() # 截取整個屏幕
screenshot.save('screenshot.png') # 保存截圖#圖像識別
button_location = pyautogui.locateOnScreen('button.png') # 在屏幕上查找圖片
if button_location:print(f"找到按鈕,位置: {button_location}")pyautogui.click(button_location) # 點擊找到的按鈕
else:print("未找到按鈕")
- 總結
PyAutoGUI 是一個功能強大且易于使用的自動化工具,適用于 GUI 自動化、測試腳本、游戲自動化等場景。通過掌握其基本功能,你可以輕松實現鼠標、鍵盤的自動化操作。如果需要更復雜的操作,可以結合圖像識別和邏輯控制來實現。