pyautogui là thư viện cross-platform điều khiển chuột/bàn phím, tự động hóa GUI.
Cài đặt
pip install pyautogui
Linux có thể cần: sudo apt-get install python3-xlib scrot
Điều khiển chuột
import pyautogui
# Kích thước màn hình
width, height = pyautogui.size()
print(f"Screen: {width}x{height}")
# Vị trí chuột hiện tại
print(pyautogui.position()) # Point(x=..., y=...)
# Di chuyển chuột
pyautogui.moveTo(100, 100, duration=1) # Tuyệt đối
pyautogui.moveRel(50, 0, duration=0.5) # Tương đối
pyautogui.dragTo(200, 200, duration=1) # Kéo thả
pyautogui.dragRel(30, 30, duration=0.5)
# Click
pyautogui.click(100, 100) # Click trái
pyautogui.rightClick(100, 100) # Click phải
pyautogui.doubleClick(100, 100) # Double click
pyautogui.click(clicks=3, interval=0.2) # Multi-click
# Cuộn
pyautogui.scroll(10) # Cuộn lên
pyautogui.scroll(-10) # Cuộn xuống
Điều khiển bàn phím
typewrite() - Gõ chuỗi
pyautogui.typewrite('Hello World!') # Ngay lập tức
pyautogui.typewrite('Hello World!', interval=0.1) # Delay 0.1s/ký tự
press(), keyDown(), keyUp() - Phím đặc biệt
pyautogui.press('enter')
pyautogui.press('f1')
pyautogui.press(['left', 'left', 'left']) # Nhiều phím
# Hold key
pyautogui.keyDown('ctrl')
pyautogui.press('c')
pyautogui.keyUp('ctrl')
hotkey() - Phím tắt (shortcut)
pyautogui.hotkey('ctrl', 'shift', 'esc') # Mở Task Manager (Windows)
pyautogui.hotkey('ctrl', 'c') # Copy
pyautogui.hotkey('ctrl', 'v') # Paste
Danh sách phím hợp lệ (pyautogui.KEYBOARD_KEYS)
Bao gồm: 'enter', 'esc', 'tab', 'shift', 'ctrl', 'alt', 'f1'..'f24', 'left', 'right', 'up', 'down', 'home', 'end', 'pageup', 'pagedown', 'backspace', 'delete', 'insert', 'capslock', 'numlock', 'printscreen', 'scrolllock', 'pause', 'win', 'command', 'option', ...
Ví dụ thực tế: Tự động mở Notepad và gõ text
import pyautogui
import time
import subprocess
# Mở Notepad
subprocess.Popen(['notepad.exe'])
time.sleep(1) # Chờ mở
# Gõ text
pyautogui.typewrite('Automated with pyautogui!\n', interval=0.05)
# Lưu file (Ctrl+S)
pyautogui.hotkey('ctrl', 's')
time.sleep(0.5)
pyautogui.typewrite('auto_note.txt')
pyautogui.press('enter')
An toàn & Best Practices
- Fail-safe: Di chuyển chuột góc trên-trái (0,0) -> pyautogui ném exception
FailSafeException. Bật/tắt:pyautogui.FAILSAFE = True/False. - Pause:
pyautogui.PAUSE = 0.1(delay mặc định sau mỗi lệnh). - Luôn test trên môi trường an toàn trước khi chạy production.
- Tránh hardcode tọa độ; dùng
locateOnScreen()tìm ảnh để click vị trí động.
Image Recognition (Tìm ảnh trên màn hình)
# Tìm nút button.png trên màn hình
location = pyautogui.locateOnScreen('button.png', confidence=0.8)
if location:
center = pyautogui.center(location)
pyautogui.click(center)
Yêu cầu cài thêm: pip install opencv-python cho parameter confidence.