PyAutoGUI 완벽 가이드 – 파이썬 GUI 자동화의 모든 것

반복적인 마우스 클릭과 키보드 입력 작업이 지겹지 않으신가요? 데이터 입력, 폼 작성, 게임 매크로, 웹 테스트 등 모든 GUI 작업을 자동화하고 싶으신가요? 이 글에서는 PyAutoGUI를 활용한 실전 자동화 기법을 완벽하게 알려드립니다.

PyAutoGUI란?

PyAutoGUI는 마우스와 키보드를 프로그래밍으로 제어하는 크로스 플랫폼 파이썬 라이브러리입니다. 화면의 특정 위치 클릭, 텍스트 입력, 스크린샷 캡처, 이미지 인식을 통한 자동 클릭 등 모든 GUI 작업을 자동화할 수 있습니다. Windows, macOS, Linux 모두 지원합니다.

설치 방법

기본 설치

# PyAutoGUI 설치
pip install pyautogui

# 이미지 인식을 위한 Pillow
pip install pillow

# 고급 이미지 인식 (선택사항)
pip install opencv-python

# 한글 입력을 위한 클립보드 (선택사항)
pip install pyperclip

설치 확인

import pyautogui

print(f"PyAutoGUI 버전: {pyautogui.__version__}")
print(f"화면 크기: {pyautogui.size()}")
print(f"마우스 위치: {pyautogui.position()}")
# PyAutoGUI 버전: 0.9.54
# 화면 크기: Size(width=1920, height=1080)
# 마우스 위치: Point(x=500, y=300)

마우스 제어

마우스 이동

import pyautogui
import time

# 절대 좌표로 즉시 이동
pyautogui.moveTo(100, 100)

# 2초 동안 부드럽게 이동
pyautogui.moveTo(500, 500, duration=2)

# 상대 좌표로 이동 (현재 위치 기준)
pyautogui.move(100, 0)  # 오른쪽으로 100픽셀
pyautogui.move(0, -100)  # 위로 100픽셀

# 현재 마우스 위치 확인
x, y = pyautogui.position()
print(f"현재 위치: ({x}, {y})")

duration 매개변수: 사람처럼 자연스러운 움직임을 만듭니다.

마우스 클릭

import pyautogui

# 현재 위치에서 왼쪽 클릭
pyautogui.click()

# 특정 위치 클릭
pyautogui.click(100, 200)

# 시간 간격을 두고 부드럽게
pyautogui.click(300, 400, duration=1)

# 더블 클릭
pyautogui.doubleClick()
pyautogui.doubleClick(150, 250)

# 오른쪽 클릭
pyautogui.rightClick()
pyautogui.rightClick(200, 300)

# 가운데 버튼 클릭
pyautogui.middleClick()

# 여러 번 클릭
pyautogui.click(clicks=5, interval=0.25)  # 0.25초 간격으로 5번

마우스 드래그

import pyautogui

# 상대 좌표로 드래그
pyautogui.drag(100, 0, duration=1)  # 오른쪽으로 100픽셀

# 절대 좌표로 드래그
pyautogui.dragTo(500, 500, duration=2)

# 버튼 지정
pyautogui.drag(200, 0, button='left')
pyautogui.drag(100, 100, button='right')

# 파일 드래그 앤 드롭 예제
pyautogui.moveTo(100, 100)  # 파일 위치
pyautogui.drag(400, 300, duration=1)  # 대상 위치로 드래그

스크롤

import pyautogui

# 위로 스크롤 (양수)
pyautogui.scroll(10)

# 아래로 스크롤 (음수)
pyautogui.scroll(-10)

# 특정 위치에서 스크롤
pyautogui.scroll(5, x=500, y=500)

# 부드러운 스크롤
import time
for _ in range(10):
    pyautogui.scroll(-1)
    time.sleep(0.1)

# 수평 스크롤 (일부 환경)
pyautogui.hscroll(5)  # 오른쪽
pyautogui.hscroll(-5)  # 왼쪽

키보드 제어

텍스트 입력

import pyautogui

# 영문 텍스트 입력
pyautogui.write('Hello World')

# 천천히 입력 (사람처럼)
pyautogui.write('Python', interval=0.25)

# 숫자와 기본 특수문자
pyautogui.write('test@example.com')
pyautogui.write('Price: $99.99')

주의: write()는 영문, 숫자, 기본 특수문자만 지원합니다.

특수 키 입력

import pyautogui

# 단일 키 누르기
pyautogui.press('enter')
pyautogui.press('esc')
pyautogui.press('tab')
pyautogui.press('space')
pyautogui.press('backspace')
pyautogui.press('delete')

# 화살표 키
pyautogui.press('up')
pyautogui.press('down')
pyautogui.press('left')
pyautogui.press('right')

# 펑션 키
pyautogui.press('f1')
pyautogui.press('f12')

# 여러 번 누르기
pyautogui.press('down', presses=5, interval=0.5)

키 조합 (단축키)

import pyautogui

# Ctrl + C (복사)
pyautogui.hotkey('ctrl', 'c')

# Ctrl + V (붙여넣기)
pyautogui.hotkey('ctrl', 'v')

# Ctrl + A (전체 선택)
pyautogui.hotkey('ctrl', 'a')

# Ctrl + Shift + S (다른 이름으로 저장)
pyautogui.hotkey('ctrl', 'shift', 's')

# Alt + Tab (창 전환)
pyautogui.hotkey('alt', 'tab')

# Alt + F4 (창 닫기)
pyautogui.hotkey('alt', 'f4')

# Windows + R (실행 대화상자)
pyautogui.hotkey('win', 'r')

# Command + Space (macOS Spotlight)
pyautogui.hotkey('command', 'space')

키 누르기/떼기

import pyautogui
import time

# 키를 누른 상태 유지
pyautogui.keyDown('shift')
pyautogui.press('left')  # Shift + 왼쪽 (텍스트 선택)
pyautogui.press('left')
pyautogui.press('left')
pyautogui.keyUp('shift')

# 게임 예제: W키 3초간 누르기
pyautogui.keyDown('w')
time.sleep(3)
pyautogui.keyUp('w')

# Ctrl 누른 채 여러 작업
pyautogui.keyDown('ctrl')
pyautogui.press('a')  # 전체 선택
pyautogui.press('c')  # 복사
pyautogui.keyUp('ctrl')

한글 입력 해결

pyperclip 활용

import pyautogui
import pyperclip

def write_korean(text):
    """클립보드를 이용한 한글 입력"""
    pyperclip.copy(text)
    pyautogui.hotkey('ctrl', 'v')

# 사용 예시
write_korean('안녕하세요')
pyautogui.press('enter')
write_korean('파이썬 자동화')

자동 감지 함수

import pyautogui
import pyperclip

def smart_write(text, interval=0.1):
    """영문은 write(), 한글은 클립보드 사용"""
    if any(ord(char) > 127 for char in text):
        # 한글 포함
        pyperclip.copy(text)
        pyautogui.hotkey('ctrl', 'v')
    else:
        # 영문만
        pyautogui.write(text, interval=interval)

# 사용
smart_write('Hello')  # write() 사용
smart_write('안녕하세요')  # 클립보드 사용
smart_write('Python 파이썬 3.12')  # 클립보드 사용

스크린샷 및 이미지 인식

스크린샷 캡처

import pyautogui

# 전체 화면 스크린샷
screenshot = pyautogui.screenshot()
screenshot.save('screenshot.png')

# 특정 영역만 캡처 (x, y, width, height)
region = pyautogui.screenshot(region=(0, 0, 300, 400))
region.save('region.png')

# PIL Image 객체로 반환
from PIL import Image
img = pyautogui.screenshot()
print(type(img))  # <class 'PIL.Image.Image'>

# NumPy 배열로 변환
import numpy as np
img_array = np.array(img)

화면에서 이미지 찾기

import pyautogui

# 이미지 위치 찾기
try:
    location = pyautogui.locateOnScreen('button.png')
    print(f"위치: {location}")
    # Box(left=100, top=200, width=50, height=30)

    # 중심점 좌표
    center = pyautogui.center(location)
    print(f"중심점: {center}")
    # Point(x=125, y=215)

    # 중심점을 바로 찾기
    center_pos = pyautogui.locateCenterOnScreen('button.png')
    if center_pos:
        pyautogui.click(center_pos)

except pyautogui.ImageNotFoundException:
    print("이미지를 찾을 수 없습니다")

준비물: 클릭할 버튼의 스크린샷을 미리 저장해야 합니다.

이미지 인식 고급 옵션

import pyautogui

# 신뢰도 조절 (OpenCV 필요)
location = pyautogui.locateOnScreen('button.png', confidence=0.8)
# 80% 이상 유사하면 찾음

# 그레이스케일로 찾기 (속도 향상)
location = pyautogui.locateOnScreen('icon.png', grayscale=True)

# 특정 영역에서만 찾기
location = pyautogui.locateOnScreen('button.png', region=(0, 0, 800, 600))

# 모든 일치 항목 찾기
locations = list(pyautogui.locateAllOnScreen('icon.png'))
for loc in locations:
    center = pyautogui.center(loc)
    print(f"발견 위치: {center}")

픽셀 색상 확인

import pyautogui

# 특정 좌표의 색상 확인
color = pyautogui.pixel(100, 200)
print(color)  # (255, 0, 0) - RGB 튜플

# 색상 일치 여부
if pyautogui.pixelMatchesColor(100, 200, (255, 0, 0)):
    print("빨간색입니다")

# 허용 오차 포함
if pyautogui.pixelMatchesColor(100, 200, (255, 0, 0), tolerance=10):
    print("거의 빨간색입니다")

# 특정 색상이 나타날 때까지 대기
import time
while not pyautogui.pixelMatchesColor(500, 500, (0, 255, 0)):
    time.sleep(0.5)
print("초록색 감지!")

화면 정보

화면 크기 및 마우스 위치

import pyautogui

# 화면 해상도
width, height = pyautogui.size()
print(f"화면 크기: {width} x {height}")

# 현재 마우스 위치
x, y = pyautogui.position()
print(f"마우스: ({x}, {y})")

# 화면 중앙 좌표
center_x = width // 2
center_y = height // 2
pyautogui.moveTo(center_x, center_y)

# 화면 내 여부 확인
if pyautogui.onScreen(x, y):
    print("화면 안에 있습니다")

실시간 마우스 추적

import pyautogui
import time

def track_mouse(duration=10):
    """마우스 위치를 실시간으로 출력"""
    print(f"{duration}초 동안 추적... (Ctrl+C로 종료)")

    try:
        start = time.time()
        while time.time() - start < duration:
            x, y = pyautogui.position()
            print(f"\\\\rX: {x:4d}  Y: {y:4d}", end='')
            time.sleep(0.1)
    except KeyboardInterrupt:
        print("\\\\n추적 종료")

track_mouse(30)

좌표 찾기: 클릭할 위치의 정확한 좌표를 찾는 데 유용합니다.

메시지 박스

import pyautogui

# 알림 메시지
pyautogui.alert('작업이 완료되었습니다!', '알림')

# 확인/취소
result = pyautogui.confirm('계속하시겠습니까?', '확인')
if result == 'OK':
    print("계속 진행")
elif result == 'Cancel':
    print("취소됨")

# 커스텀 버튼
answer = pyautogui.confirm('파일을 저장하시겠습니까?',
                           buttons=['저장', '저장 안함', '취소'])
print(f"선택: {answer}")

# 텍스트 입력
name = pyautogui.prompt('이름을 입력하세요:')
print(f"입력된 이름: {name}")

# 비밀번호 입력 (마스킹)
password = pyautogui.password('비밀번호:')
if password:
    print("비밀번호 입력됨")

안전 장치

페일세이프 (Fail-Safe)

import pyautogui

# 페일세이프 활성화 (기본값)
pyautogui.FAILSAFE = True

# 마우스를 화면 왼쪽 상단 (0, 0)으로 이동하면
# pyautogui.FailSafeException 발생하여 프로그램 중단

# 비활성화 (비추천)
pyautogui.FAILSAFE = False

긴급 중단: 자동화가 잘못되면 마우스를 왼쪽 상단으로 이동해 중단하세요.

전역 지연 시간

import pyautogui

# 모든 PyAutoGUI 함수 호출 전 대기
pyautogui.PAUSE = 1  # 1초

# 이제 모든 명령 사이에 1초 대기
pyautogui.click(100, 100)  # 1초 대기 후 클릭
pyautogui.write('Hello')   # 1초 대기 후 입력
pyautogui.press('enter')   # 1초 대기 후 Enter

# 안정성 향상
pyautogui.PAUSE = 0.5  # 0.5초면 적당

실전 자동화 예제

예제 1: 메모장 자동화

import pyautogui
import time

def notepad_automation():
    print("메모장 자동화 시작...")

    # Windows 실행 창 열기
    pyautogui.hotkey('win', 'r')
    time.sleep(0.5)

    # notepad 입력 및 실행
    pyautogui.write('notepad')
    pyautogui.press('enter')
    time.sleep(1)

    # 텍스트 입력
    text_lines = [
        'PyAutoGUI 자동화 예제',
        '',
        '1. 마우스 제어',
        '2. 키보드 제어',
        '3. 스크린샷',
        '4. 이미지 인식'
    ]

    for line in text_lines:
        pyautogui.write(line, interval=0.05)
        pyautogui.press('enter')
        time.sleep(0.2)

    # 저장
    time.sleep(1)
    pyautogui.hotkey('ctrl', 's')
    time.sleep(0.5)

    # 파일명 입력
    pyautogui.write('pyautogui_test.txt')
    pyautogui.press('enter')

    print("✅ 메모장 자동화 완료!")

notepad_automation()

예제 2: 구글 검색 자동화

import pyautogui
import time
import webbrowser

def google_search_automation(query):
    # 브라우저 열기
    webbrowser.open('<https://www.google.com>')
    time.sleep(3)  # 페이지 로딩 대기

    # 검색창 클릭 (구글 화면 중앙)
    width, height = pyautogui.size()
    pyautogui.click(width // 2, height // 2)
    time.sleep(0.5)

    # 검색어 입력
    import pyperclip
    pyperclip.copy(query)
    pyautogui.hotkey('ctrl', 'v')
    time.sleep(0.5)

    # 검색 실행
    pyautogui.press('enter')
    time.sleep(2)

    # 스크린샷 저장
    pyautogui.screenshot(f'search_{query}.png')

    print(f"✅ '{query}' 검색 완료!")

# 사용
google_search_automation('파이썬 자동화')

예제 3: 엑셀 데이터 입력

import pyautogui
import time

def excel_data_entry():
    """엑셀에 데이터 자동 입력"""

    data = [
        ['이름', '나이', '부서'],
        ['김철수', '28', '개발팀'],
        ['이영희', '32', '디자인팀'],
        ['박민수', '25', '기획팀'],
        ['정수아', '30', '마케팅팀']
    ]

    print("5초 후 엑셀에 데이터 입력 시작...")
    print("엑셀을 열고 첫 번째 셀(A1)을 선택하세요")
    time.sleep(5)

    for row in data:
        for cell in row:
            import pyperclip
            pyperclip.copy(str(cell))
            pyautogui.hotkey('ctrl', 'v')
            pyautogui.press('tab')  # 다음 셀
            time.sleep(0.2)

        pyautogui.press('enter')  # 다음 행
        time.sleep(0.2)

    print("✅ 데이터 입력 완료!")

excel_data_entry()

예제 4: 이미지 기반 자동 클릭

import pyautogui
import time

def wait_and_click_image(image_path, timeout=30):
    """이미지가 나타나면 클릭"""
    print(f"'{image_path}' 이미지를 찾는 중...")

    start_time = time.time()

    while time.time() - start_time < timeout:
        try:
            location = pyautogui.locateCenterOnScreen(image_path, confidence=0.8)

            if location:
                print(f"✅ 이미지 발견: {location}")
                pyautogui.click(location)
                return True

        except pyautogui.ImageNotFoundException:
            pass

        time.sleep(1)

    print(f"❌ {timeout}초 동안 이미지를 찾지 못했습니다")
    return False

# 사용 예시
if wait_and_click_image('login_button.png', timeout=60):
    print("로그인 버튼 클릭 성공")
    time.sleep(2)

    # 다음 동작
    pyautogui.write('username')
    pyautogui.press('tab')
    pyautogui.write('password')
    pyautogui.press('enter')

예제 5: 폼 자동 입력

import pyautogui
import pyperclip
import time

def fill_web_form():
    """웹 폼 자동 입력"""

    form_data = {
        'name': '홍길동',
        'email': 'hong@example.com',
        'phone': '010-1234-5678',
        'address': '서울특별시 강남구',
        'message': '안녕하세요. 문의사항입니다.'
    }

    print("3초 후 폼 입력 시작...")
    print("첫 번째 입력 필드에 포커스를 맞추세요")
    time.sleep(3)

    for field, value in form_data.items():
        print(f"입력 중: {field}")

        # 한글 포함 여부 확인
        if any(ord(char) > 127 for char in value):
            pyperclip.copy(value)
            pyautogui.hotkey('ctrl', 'v')
        else:
            pyautogui.write(value)

        pyautogui.press('tab')  # 다음 필드
        time.sleep(0.5)

    # 제출 버튼 클릭 (이미지 인식)
    submit_location = pyautogui.locateCenterOnScreen('submit_button.png')
    if submit_location:
        pyautogui.click(submit_location)
        print("✅ 폼 제출 완료!")
    else:
        print("⚠️ 제출 버튼을 찾을 수 없습니다")

fill_web_form()

예제 6: 게임 자동화 (간단한 클릭 게임)

import pyautogui
import time

def auto_clicker(x, y, clicks=100, interval=0.5):
    """자동 클릭 프로그램"""

    print(f"5초 후 ({x}, {y}) 위치를 {clicks}번 클릭합니다")
    print("마우스를 (0, 0)으로 이동하면 중단됩니다")
    time.sleep(5)

    for i in range(clicks):
        try:
            pyautogui.click(x, y)
            print(f"{i+1}/{clicks} 클릭 완료", end='\\\\r')
            time.sleep(interval)
        except pyautogui.FailSafeException:
            print("\\\\n⚠️ 페일세이프 작동! 중단됨")
            break

    print("\\\\n✅ 자동 클릭 완료!")

# 화면 중앙 자동 클릭
width, height = pyautogui.size()
auto_clicker(width // 2, height // 2, clicks=50, interval=0.3)

고급 기법

조건부 대기

import pyautogui
import time

def wait_for_condition(check_function, timeout=30, check_interval=1):
    """조건이 충족될 때까지 대기"""
    start_time = time.time()

    while time.time() - start_time < timeout:
        if check_function():
            return True
        time.sleep(check_interval)

    return False

# 사용 예시: 특정 색상 감지까지 대기
def is_red_pixel():
    return pyautogui.pixelMatchesColor(500, 500, (255, 0, 0), tolerance=10)

if wait_for_condition(is_red_pixel, timeout=60):
    print("빨간색 픽셀 감지!")
    pyautogui.click(500, 500)

로깅 시스템

import pyautogui
import time
from datetime import datetime

class AutomationLogger:
    def __init__(self, log_file='automation.log'):
        self.log_file = log_file
        self.log("=== 자동화 시작 ===")

    def log(self, message):
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        log_entry = f"[{timestamp}] {message}"
        print(log_entry)

        with open(self.log_file, 'a', encoding='utf-8') as f:
            f.write(log_entry + '\\\\n')

    def click(self, x, y):
        self.log(f"CLICK: ({x}, {y})")
        pyautogui.click(x, y)

    def write(self, text):
        self.log(f"WRITE: {text}")
        pyautogui.write(text)

    def press(self, key):
        self.log(f"PRESS: {key}")
        pyautogui.press(key)

# 사용 예시
logger = AutomationLogger()
logger.click(100, 200)
logger.write('Hello')
logger.press('enter')

에러 복구

import pyautogui
import time

def safe_automation(steps):
    """에러가 발생해도 계속 진행"""

    for i, step in enumerate(steps, 1):
        try:
            print(f"[{i}/{len(steps)}] {step['description']}")

            if step['type'] == 'click':
                pyautogui.click(step['x'], step['y'])
            elif step['type'] == 'write':
                pyautogui.write(step['text'])
            elif step['type'] == 'press':
                pyautogui.press(step['key'])

            time.sleep(step.get('wait', 0.5))

        except Exception as e:
            print(f"❌ 오류 발생: {e}")

            # 스크린샷 저장
            pyautogui.screenshot(f'error_{i}.png')

            # 다음 단계로 계속
            continue

    print("✅ 자동화 완료!")

# 사용 예시
automation_steps = [
    {'type': 'click', 'x': 100, 'y': 100, 'description': '시작 버튼 클릭'},
    {'type': 'write', 'text': 'test', 'description': '텍스트 입력'},
    {'type': 'press', 'key': 'enter', 'description': 'Enter 키', 'wait': 2}
]

safe_automation(automation_steps)

문제 해결

macOS 권한 설정

# 시스템 환경설정 > 보안 및 개인 정보 보호 > 개인 정보 보호
# > 손쉬운 사용 > Python/터미널 체크
# > 화면 기록 > Python/터미널 체크

이미지 인식이 안 될 때

# 1. confidence 낮추기
location = pyautogui.locateOnScreen('image.png', confidence=0.7)

# 2. 그레이스케일 사용
location = pyautogui.locateOnScreen('

image.png’, grayscale=True)

3. 특정 영역으로 범위 좁히기

location = pyautogui.locateOnScreen(‘image.png’, region=(0, 0, 1000, 800))

4. 이미지 크기 조정

from PIL import Image img = Image.open(‘button.png’) img_resized = img.resize((int(img.width * 0.8), int(img.height * 0.8))) img_resized.save(‘button_small.png’)

5. 디버깅: 현재 화면과 비교

screen = pyautogui.screenshot() screen.save(‘current_screen.png’)

육안으로 이미지와 화면 비교

### 속도가 너무 느릴 때

```python
# PAUSE 값 줄이기
pyautogui.PAUSE = 0.1  # 기본값 0.1초

# duration 제거
pyautogui.moveTo(500, 500)  # duration 없이 즉시 이동

# 불필요한 time.sleep() 제거

멀티 모니터 환경

import pyautogui

# 음수 좌표로 왼쪽 모니터 접근
pyautogui.moveTo(-500, 500)

# 큰 양수 좌표로 오른쪽 모니터 접근
pyautogui.moveTo(2500, 500)

# 화면 경계 확인
width, height = pyautogui.size()
print(f"주 모니터 크기: {width}x{height}")

실무 활용 팁

1. 작업 전 대기 시간 설정

import pyautogui
import time

def start_with_countdown(seconds=5):
    """카운트다운 후 시작"""
    print(f"{seconds}초 후 시작됩니다...")
    for i in range(seconds, 0, -1):
        print(f"{i}...")
        time.sleep(1)
    print("시작!")

# 사용
start_with_countdown(5)
# 이후 자동화 코드 실행

2. 스크린샷으로 진행 상황 기록

import pyautogui
from datetime import datetime

def capture_progress(step_name):
    """단계별 스크린샷 저장"""
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    filename = f"{step_name}_{timestamp}.png"
    pyautogui.screenshot(filename)
    print(f"📸 스크린샷 저장: {filename}")

# 사용
capture_progress('step1_login')
# ... 작업 수행 ...
capture_progress('step2_form_fill')
# ... 작업 수행 ...
capture_progress('step3_complete')

3. 설정 파일로 좌표 관리

import pyautogui
import json

# config.json 파일
# {
#     "login_button": [100, 200],
#     "username_field": [150, 250],
#     "password_field": [150, 300],
#     "submit_button": [200, 400]
# }

def load_coordinates(config_file='config.json'):
    """설정 파일에서 좌표 로드"""
    with open(config_file, 'r') as f:
        return json.load(f)

def automated_login(config_file='config.json'):
    coords = load_coordinates(config_file)

    # 로그인 버튼 클릭
    pyautogui.click(*coords['login_button'])
    time.sleep(1)

    # 사용자명 입력
    pyautogui.click(*coords['username_field'])
    pyautogui.write('myusername')

    # 비밀번호 입력
    pyautogui.click(*coords['password_field'])
    pyautogui.write('mypassword')

    # 제출
    pyautogui.click(*coords['submit_button'])

    print("✅ 로그인 완료")

4. 재시도 로직

import pyautogui
import time

def click_with_retry(x, y, max_attempts=3, wait_time=2):
    """실패 시 재시도하는 클릭"""
    for attempt in range(1, max_attempts + 1):
        try:
            print(f"클릭 시도 {attempt}/{max_attempts}")
            pyautogui.click(x, y)

            # 클릭 성공 확인 (예: 특정 색상 체크)
            time.sleep(wait_time)
            if pyautogui.pixelMatchesColor(x, y, (0, 255, 0)):
                print("✅ 클릭 성공")
                return True

        except Exception as e:
            print(f"❌ 시도 실패: {e}")

        if attempt < max_attempts:
            print(f"{wait_time}초 후 재시도...")
            time.sleep(wait_time)

    print("❌ 모든 시도 실패")
    return False

# 사용
click_with_retry(100, 200, max_attempts=5)

5. 병렬 작업 (여러 작업 동시 실행)

import pyautogui
import threading
import time

def task1():
    """작업 1: 왼쪽 영역 처리"""
    pyautogui.click(100, 100)
    time.sleep(1)
    pyautogui.write('Task 1')
    print("Task 1 완료")

def task2():
    """작업 2: 오른쪽 영역 처리"""
    pyautogui.click(500, 100)
    time.sleep(1)
    pyautogui.write('Task 2')
    print("Task 2 완료")

# 순차 실행
# task1()
# task2()

# 병렬 실행 (주의: PyAutoGUI는 단일 마우스/키보드만 제어)
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2)

t1.start()
time.sleep(0.5)  # 충돌 방지를 위한 짧은 딜레이
t2.start()

t1.join()
t2.join()

종합 예제: 완전 자동화 스크립트

import pyautogui
import pyperclip
import time
from datetime import datetime

class WebFormAutomation:
    """웹 폼 자동 입력 자동화 클래스"""

    def __init__(self):
        self.log_file = f"automation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
        pyautogui.PAUSE = 0.5
        pyautogui.FAILSAFE = True

    def log(self, message):
        """로그 기록"""
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        log_entry = f"[{timestamp}] {message}"
        print(log_entry)

        with open(self.log_file, 'a', encoding='utf-8') as f:
            f.write(log_entry + '\\\\n')

    def safe_click(self, x, y, description=""):
        """안전한 클릭"""
        try:
            self.log(f"클릭 시도: ({x}, {y}) {description}")
            pyautogui.click(x, y)
            time.sleep(0.3)
            return True
        except Exception as e:
            self.log(f"클릭 실패: {e}")
            return False

    def safe_write(self, text, description=""):
        """안전한 텍스트 입력 (한글 지원)"""
        try:
            self.log(f"입력 시도: {description}")
            if any(ord(char) > 127 for char in text):
                pyperclip.copy(text)
                pyautogui.hotkey('ctrl', 'v')
            else:
                pyautogui.write(text)
            time.sleep(0.3)
            return True
        except Exception as e:
            self.log(f"입력 실패: {e}")
            return False

    def wait_for_image(self, image_path, timeout=30):
        """이미지가 나타날 때까지 대기"""
        self.log(f"이미지 대기: {image_path}")
        start_time = time.time()

        while time.time() - start_time < timeout:
            try:
                location = pyautogui.locateCenterOnScreen(image_path, confidence=0.8)
                if location:
                    self.log(f"이미지 발견: {location}")
                    return location
            except:
                pass
            time.sleep(1)

        self.log(f"이미지 타임아웃: {image_path}")
        return None

    def fill_form(self, form_data):
        """폼 자동 입력"""
        self.log("=== 폼 입력 시작 ===")

        # 시작 대기
        print("5초 후 시작됩니다. 첫 번째 필드에 포커스를 맞추세요")
        time.sleep(5)

        # 각 필드 입력
        for field_name, value in form_data.items():
            if not self.safe_write(value, field_name):
                self.log(f"필드 입력 실패: {field_name}")
                pyautogui.screenshot(f'error_{field_name}.png')

            pyautogui.press('tab')
            time.sleep(0.5)

        self.log("=== 폼 입력 완료 ===")

        # 완료 스크린샷
        pyautogui.screenshot('form_completed.png')

    def submit_form(self, button_image='submit_button.png'):
        """제출 버튼 클릭"""
        self.log("제출 버튼 찾기")

        location = self.wait_for_image(button_image, timeout=10)
        if location:
            pyautogui.click(location)
            self.log("✅ 폼 제출 완료")
            return True
        else:
            self.log("❌ 제출 버튼을 찾을 수 없습니다")
            return False

# 사용 예시
def main():
    automation = WebFormAutomation()

    # 입력할 데이터
    form_data = {
        'name': '홍길동',
        'email': 'hong@example.com',
        'phone': '010-1234-5678',
        'company': '파이썬 주식회사',
        'message': '안녕하세요. 문의드립니다.'
    }

    # 폼 입력
    automation.fill_form(form_data)

    # 제출
    automation.submit_form('submit_button.png')

    print(f"\\\\n📋 로그 파일: {automation.log_file}")

if __name__ == '__main__':
    main()

키보드 키 참조표

# 주요 키 이름 목록
KEYS = {
    '문자': ['a-z', '0-9'],
    '특수문자': [',', '.', '/', ';', "'", '[', ']', '\\\\\\\\', '-', '='],
    '방향키': ['up', 'down', 'left', 'right'],
    '편집': ['backspace', 'delete', 'insert', 'home', 'end', 'pageup', 'pagedown'],
    '기능': ['f1', 'f2', ..., 'f12'],
    '수정': ['ctrl', 'shift', 'alt', 'win', 'command', 'option'],
    '시스템': ['enter', 'return', 'esc', 'tab', 'space', 'capslock'],
    '넘패드': ['num0', 'num1', ..., 'num9', 'add', 'subtract', 'multiply', 'divide']
}

# 전체 키 목록 확인
import pyautogui
print(pyautogui.KEYBOARD_KEYS)

성능 최적화

이미지 인식 속도 향상

import pyautogui

# 1. 그레이스케일 사용 (3배 빠름)
location = pyautogui.locateOnScreen('button.png', grayscale=True)

# 2. 검색 영역 제한 (10배 빠름)
location = pyautogui.locateOnScreen('button.png', region=(0, 0, 800, 600))

# 3. confidence 낮추기 (더 빠르지만 정확도 감소)
location = pyautogui.locateOnScreen('button.png', confidence=0.7)

# 4. 이미지 크기 줄이기
from PIL import Image
img = Image.open('large_button.png')
img_small = img.resize((img.width // 2, img.height // 2))
img_small.save('small_button.png')

불필요한 대기 제거

# 나쁜 예
pyautogui.click(100, 100)
time.sleep(2)  # 불필요하게 길게
pyautogui.click(200, 200)
time.sleep(2)

# 좋은 예
pyautogui.PAUSE = 0.1  # 전역 대기 시간 짧게
pyautogui.click(100, 100)
pyautogui.click(200, 200)

# 필요한 곳만 대기
pyautogui.click(300, 300)
time.sleep(1)  # 페이지 로딩 대기가 필요한 경우만

보안 및 윤리적 고려사항

주의사항

"""
⚠️ PyAutoGUI 사용 시 주의사항:

1. 게임 자동화: 대부분의 온라인 게임은 매크로 사용을 금지합니다
2. 웹사이트: robots.txt 및 이용약관을 확인하세요
3. 개인정보: 비밀번호 등을 코드에 하드코딩하지 마세요
4. 법적 책임: 자동화로 인한 문제는 사용자 책임입니다

✅ 올바른 사용:
- 반복적인 업무 자동화
- 테스트 자동화
- 데이터 입력 자동화
- 개인 생산성 향상

❌ 부적절한 사용:
- 게임 부정 행위
- 스팸 생성
- 무단 데이터 수집
- 시스템 공격
"""

마치며

PyAutoGUI는 마우스 클릭(click()), 키보드 입력(write(), press()), 스크린샷(screenshot()), 이미지 인식(locateOnScreen())의 4가지 핵심 기능으로 모든 GUI 작업을 자동화할 수 있습니다.

페일세이프로 안전장치를 설정하고, 한글은 pyperclip으로 클립보드를 활용하며, 이미지 인식으로 유연한 자동화를 구현하세요. 반복적인 데이터 입력, 폼 작성, 테스트 자동화 등 다양한 실무 작업에 즉시 적용할 수 있습니다.

이 가이드의 예제를 활용해 업무 효율을 극대화하고, 반복 작업에서 해방되세요!


참고 자료

댓글 남기기