[References]
https://blog.naver.com/wevebeen/222035865428
https://blog.naver.com/dsz08082/222149090121
https://wikidocs.net/85722
https://blankspace-dev.tistory.com/405?category=705032
1. pyAutoGui
프로그래밍 방식으로 마우스와 키보드를 제어하는 파이썬 모듈
[References] https://pyautogui.readthedocs.io/en/latest
2. 주요 기능
마우스를 이동하고 클릭, 다른 응용 프로그램의 창을 클릭하거나 입력
스크린 샷을 찍고 이미지가 주어지면 화면에서 찾음
Windows 운영체제에서 응용 프로그램의 창을 찾아 이동, 크기 조정, 최대화, 최소화 등의 기능 수행
스크립트를 실행할 동안 상호 작용을 위한 메시지 상자 표시
3. 설치
pip install pyautogui
4. 명령어
1) 모니터 사이즈
size()
현재 사용하고 있는 모니터의 사이즈(width, height) 반환한다.
import pyautogui
screenWidth, screenHeight = pyautogui.size()
print('{0}, {1}'.format(screenWidth, screenHeight))
2) 커서 위치 반환
position()
현재 마우스 커서의 위치를 반환한다.
좌표를 알고 싶은 곳에 마우스 커서를 놓고 위 코드를 실행하면 해당 좌표를 알아낼 수 있다.
아래와 같이 터미널에서 좌표를 확인한 후, 해당 좌표를 코드에 입력해서 활용하는 것이 좋다.
import pyautogui, time
while 1:
mousePositionX, mousePositionY = pyautogui.position()
print(mousePositionX, ",", mousePositionY)
time.sleep(1)
3) 커서 위치 확인
onScreen(x, y)
x, y 좌표가 스크린 안에 위치해 있는지를 확인한다.
위치해 있으면 True를 반환하고, 위치해 있지 않으면 False를 반환한다.
import pyautogui
print(pyautogui.onScreen(1920, 1080)
# False
print(pyautogui.onScreen(1919, 1079)
# True
4) 마우스 커서 이동
moveTo(x, y)
moveTo(x, y, duration)
지정한 좌표로 마우스 커서를 이동시킬 때 사용한다.
좌표는 픽셀 단위이며, 'duration'은 커서 이동 시간이다.
import pyautogui
# 마우스를 (50, 50) 위치로 이동
pyautogui.moveTo(50, 50)
# 마우스의 x 좌표를 30으로 1초 동안 이동 (y 좌표는 고정)
pyautogui.moveTo(30, None, 1)
# 마우스의 y 좌표를 30으로 이동 (x 좌표는 고정)
pyautogui.moveTo(None, 30)
5) 마우스 커서 이동 (현재 좌표 기준)
move(x, y) 또는 moveRel(x, y)
move(x, y, duration) 또는 moveRel(x, y, duration)
현재 커서의 위치를 기준으로 지정한 거리 만큼 커서를 이동시킬 때 사용한다.
x가 양수일 때는 오른쪽으로, x가 음수일 때는 왼쪽으로 커서가 움직인다.
y가 양수일 때는 아래로, y가 음수일 때는 위로 커서가 움직인다.
import pyautogui
# 마우스 커서의 y 좌표를 현재 위치를 기준으로 100만큼 이동
pyautogui.move(0, 100)
# pyautogui.moveRel(0, 100)
# 마우스 커서의 x, y 좌표를 현재 위치를 기준으로 100만큼 3초 동안 이동
pyautogui.move(100, 100, 3)
# pyautogui.moveRel(100, 100, 3)
6) 마우스 드래그
dragTo(x, y, duration, button)
마우스 버튼을 누른 상태로 x, y 좌표를 향해 duration 동안 움직인다.
duration은 설정하지 않아도 상관없다.
button은 left, right, middle을 선택할 수 있다.
import pyautogui
# 마우스의 left 버튼을 누른 채로 (300, 300)의 위치를 향해 이동
pyautogui.dragTo(300, 300, button='left')
# 마우스의 right 버튼을 누른 채로 3초 동안 (500, 500)의 위치를 향해 이동
pyautogui.dragTo(500, 500, 3, button='right')
7) 마우스 드래그 (현재 좌표 기준)
drag(x, y, duration, button)
현재 위치를 기준으로 x, y 좌표 만큼 마우스 버튼을 누른 상태로 duration 동안 움직인다.
import pyautogui
pyautogui.drag(300, 300, button='left')
pyautogui.drag(500, 500, 3, button='right')
move, moveTo, drag, dragTo에 아래 옵션을 추가하면 커서의 움직임을 제어할 수 있다.
pyautogui.easeInQuad - 커서의 시작은 느리고 끝은 빠르게 움직인다.
pyautogui.easeOutQuad - 커서의 시작은 빠르고 끝은 느리게 움직인다.
pyautogui.easeInOutQuad - 커서의 시작과 끝은 빠르고 중간은 느리게 움직인다.
pyautogui.easeInBounce - 반동을 주며 커서를 움직인다.
import pyautogui
pyautogui.moveTo(100, 100, 2, pyautogui.easeInQuad)
pyautogui.moveTo(300, 300, 2, pyautogui.easeInBounce)
8) 마우스 버튼 누르고 떼기
mouseDown(x, y, button)
(x, y) 좌표에서 마우스 버튼을 누른다.
mouseUp(x, y, button)
(x, y) 좌표에서 마우스 버튼을 뗀다.
import pyautogui
# 현재 위치에서 마우스 왼쪽 버튼을 누른다.
pyautogui.mouseDown()
# 현재 위치에서 마우스 오른쪽 버튼을 누른다.
pyautogui.mouseDown(button='right')
# (x, y) 위치에서 마우스 오른쪽 버튼을 뗀다.
pyautogui.mouseUp(x=100, y=100, button='right')
9) 마우스 클릭하기
click(x, y, button, click, interval)
일정 간격으로 여러 번 클릭하고 싶을 경우 사용한다.
(x, y) 좌표에서 interval로 설정한 시간 동안 마우스 버튼을 click 횟수만큼 누른다.
import pyautogui
# 현재 위치에서 마우스 왼쪽 버튼을 클릭한다.
pyautogui.click()
# (x, y) 위치로 마우스 커서를 이동한 뒤 마우스 왼쪽 버튼을 클릭한다.
pyautogui.click(x=200, y=200)
# (x, y) 위치로 마우스 커서를 이동한 뒤, 마우스 오른쪽 버튼을 1초 동안 2번 클릭한다.
pyautogui.click(x=200, y=200, button='right', clicks=2, interval=1)
doubleClick()
마우스 왼쪽 버튼을 더블 클릭할 때 사용한다.
10) 마우스 스크롤하기
scroll(click, x, y)
(x, y) 위치로 이동한 후, click 수만큼 스크롤 이동을 한다.
x, y는 생략이 가능하다.
import pyautogui
# 마우스 스크롤을 20번 위로 올린다.
pyautogui.scroll(20)
# 마우스 스크롤을 20번 아래로 내린다.
pyautogui.scroll(-20)
# (x, y) 위치로 마우스 커서를 이동한 뒤, 마우스 스크롤을 10번 위로 올린다.
pyautogui.scroll(10, x=200, y=300)
11) 문자 입력
typewrite(text, interval)
원하는 내용을 interval로 설정한 시간동안 자동으로 입력한다.
오직 문자만 입력이 되며 shift 키나 Function 키는 입력이 되지 않는다.
import pyautogui
# 'hello'라는 문구를 바로 입력한다.
pyautogui.typewrite('hello')
# 'hello'라는 문구를 0.5초 주기로 한 글자씩 입력한다.
pyautogui.typewrite('hello', interval=0.5)
typewrite(['enter'])
'Enter'나 'SpaceBar' 등의 기본 키를 입력할 때 사용한다.
import pyautogui
pyautogui.typewrite(['a', 'b', 'c', 'enter'])
pyautogui.typewrite(['abc', 'enter'])
대괄호 안의 'a', 'b', 'c'는 키보드의 'a', 'b', 'c'키와 각각 매칭이 되지만, 대괄호 안의 'abc'는 키보드에 따로 지정된 키가 존재하지 않는다.
그렇기 때문에 첫 번째 코드는 'abc'가 입력된 후 'Enter'를 치지만, 두 번째 코드는 'abc'가 입력되지 않고 'Enter'만 친다.
12) 키 입력
press(key, presses, interval)
입력한 키를 누르고 떼도록 해주는 명령어이다.
'presses'는 키 내용을 몇 번 반복할 지를 지정하고 'interval'은 해당 키를 입력할 시간을 설정한다.
press() 함수에 리스트로 된 명령어 키를 함수의 인자로 보내면 typewrite()와 같은 효과를 만들 수 있다.
[Key NAME]
['\t', '\n', '\r', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e','f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', 'accept', 'add', 'alt', 'altleft', 'altright', 'apps', 'backspace', 'browserback', 'browserfavorites', 'browserforward', 'browserhome', 'browserrefresh', 'browsersearch', 'browserstop', 'capslock', 'clear', 'convert', 'ctrl', 'ctrlleft', 'ctrlright', 'decimal', 'del', 'delete', 'divide', 'down', 'end', 'enter', 'esc', 'escape', 'execute', 'f1', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f2', 'f20', 'f21', 'f22', 'f23', 'f24', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'final', 'fn', 'hanguel', 'hangul', 'hanja', 'help', 'home', 'insert', 'junja', 'kana', 'kanji', 'launchapp1', 'launchapp2', 'launchmail', 'launchmediaselect', 'left', 'modechange', 'multiply', 'nexttrack', 'nonconvert', 'num0', 'num1', 'num2', 'num3', 'num4', 'num5', 'num6', 'num7', 'num8', 'num9', 'numlock', 'pagedown', 'pageup', 'pause', 'pgdn', 'pgup', 'playpause', 'prevtrack', 'print', 'printscreen', 'prntscrn', 'prtsc', 'prtscr', 'return', 'right', 'scrolllock', 'select', 'separator', 'shift', 'shiftleft', 'shiftright', 'sleep', 'space', 'stop', 'subtract', 'tab', 'up', 'volumedown', 'volumemute', 'volumeup', 'win', 'winleft', 'winright', 'yen', 'command', 'option', 'optionleft', 'optionright']
import pyautogui
# 키보드의 왼쪽 방향키를 누름
pyautogui.press('left')
# 키보드의 shift 키를 누름
pyautogui.press('shift')
# 'a', 'b', 'c', 'd' 문자를 0.5초 간격을 두어서 두 번 입력한다.
pyautogui.press(['a', 'b', 'c', 'd'], 2, 0.5)
# 왼쪽 방향키를 세 번 입력한다.
pyautogui.press(['left', 'left', 'left'])
# 왼쪽 방향키를 세 번 입력한다.
pyautogui.press('left', presses=3)
# 'enter' 키를 3 초에 한 번씩 세 번 입력합니다.
pyautogui.press('enter', presses=3, interval=3)
keyDown(key)
입력한 키를 누르는 기능의 함수이다.
keyUp(key)
입력한 키를 떼도록 하는 기능의 함수이다.
hotkey(key, key)
여러 키를 동시에 입력하는 기능을 해준다.
import pyautogui
# ctrl 키를 누른 상태를 유지한다.
pyautogui.keyDown('ctrl')
# 'c' 키를 입력한다.
pyautogui.press('c')
# 'ctrl' 키를 뗀다.
pyautogui.keyUp('ctrl')
# 'ctrl + c' 키를 입력한다.
pyautogui.hotkey('ctrl', 'c')
13) Message Box
alert(text, title, button)
Title의 제목을 가진 Text 문자열을 출력하는 Message Box를 만든다.
Button에 대한 문자열도 직접 지정할 수 있다.
import pyautogui
pyautogui.alert(text='시험 중입니다.', title='Test')
pyautogui.alert(text='시험 중입니다.', title='Test', button='OK button')
confirm(text, title, buttons)
Title의 제목을 가진 Text 문자열을 출력하는 Message Box를 만든다.
Buttons에 List를 넣어서 여러 개의 버튼을 만들 수 있다.
confirm()은 해당 버튼을 누를 경우 문자열을 반환한다. 따라서 어떤 버튼을 눌렀는지 확인할 수 있다.
import pyautogui
answer = pyautogui.confirm(text='시험 중입니다.', title='Test', buttons=['OK', 'Cancel', 'Ignore'])
print(answer)
prompt(text, title, default)
답변을 얻기 위한 Message Box이다.
confirm()은 해당 버튼을 누를 경우 문자열을 반환한다. 따라서 어떤 버튼을 눌렀는지 확인할 수 있다.
아래 코드에서 OK를 누르면 입력한 답변을 출력할 수 있고, Cancel를 누르면 None이라는 메시지가 반환된다.
import pyautogui
answer = pyautogui.prompt(text='숫자를 입력해주세요.', title='Test', default='여기에 입력해주세요.')
print(answer)
password(text, title, default, mask)
OK와 Cancel을 가진 Message Box로 위에서 알아본 prompt()와 다른 점은 입력하는 문자를 설정한 Mask로 변경한다는 점이다.
import pyautogui
answer = pyautogui.password(text='비밀번호를 입력해주세요.', title='Test', default='123456', mask='*')
print(answer)
14) Screen Shot
pyautogui.screenshot('image.png', region=(x, y, 가로(px), 세로(px)))
모니터의 특정 위치에 해당하는 장면을 화면 캡처할 수 있다.
Screenshot 함수 전달 인자로 저장할 파일명과 좌표, 그리고 이미지의 사이즈를 지정해준다. 이 때 이미지 사이즈의 기준점은 '좌측 상단'이다.
import pyautogui
# 전체 화면 스크린 샷을 'image01.png'라는 파일명으로 저장
pyautogui.screenshot('image01.png')
# 특정 위치의 스크린 샷을 'image02.png'라는 파일명으로 저장
pyautogui.screenshot('image02.png', region=(0, 0, 200, 200))
15) 이미지 좌표 조회
locateOnScreen('image.png')
'image.png'는 파이썬 파일(.py)과 같은 폴더에 있어야 한다.
import pyautogui
pyautogui.screenshot('image.png', region=(0, 0, 200, 200))
i = pyautogui.locateOnScreen('image.png')
print(i)
# Box(left=0, top=0, width=200, height=200)
import pyautogui as pg
button5location = pg.locateOnScreen('image.png')
# Box 객체의 중앙 좌표를 리턴한다.
point = pg.center(button5location)
print(point)
위 i 값은 "(x, y, 가로pixel, 세로pixel)"와 같은 형식으로 나온다. 이를 통해 'image.png'가 현재 화면에서 어느 좌표에 있는지를 확인할 수 있다.
가로, 세로 픽셀은 지정한 파일의 '가로 x 세로' 사이즈로 나타난다.
16) 이미지 클릭
locateCenterOnScreen('image.png')
import pyautogui
pyautogui.screenshot('image.png', region=(0, 0, 200, 200))
i = pyautogui.locateOnScreen('image.png')
pyautogui.click(i)
이미지의 좌표 센터 값만 추출할 경우에는 '.locateCenterOnScreen' Method를 활용한다.
import pyautogui
pyautogui.screenshot('image.png', region=(0, 0, 200, 200))
i = pyautogui.locateCenterOnScreen('image.png')
print(i)
# Point(x=100, y=100)
pyautogui.click(i)
위 코드는 해당 이미지를 현재 화면에서 찾아 자동으로 클릭한다. 여기서 유의할 점은 '현재 화면에서' 라는 것이다.
현재 화면에서 해당 이미지가 보이지 않으면 찾을 수 없다.
5. Example
# 마우스와 키보드 조작
import pyautogui
# 모니터 사이즈 세로 크기 구하고 변수에 지정
backWidth, backHeight = pyautogui.Size()
# 마우스의 현재 위치 출력
mousePositionX, mousePositionY = pyautogui.position()
# 마우스 이동
pyautogui.moveTo(200, 150)
# 마우스 클릭
pyautogui.click()
# 마우스 현재 위치에서 이동
pyautogui.moveRel(100, 100)
# 마우스 더블 클릭
pyautogui.doubleClick()
# 마우스를 해당 지점까지 이동
pyautogui.moveTo(500, 500, duration=2, tween=pyautogui.easelnOutQuad)
# Text 입력
pyautogui.typewrite('hello', interval=0.2)
# 'esc 키' 누르기
pyautogui.press('esc')
# 'Shift 키' 누르기
pyautogui.keyDown('shift')
# 'Shift 키' 떼기
pyautogui.KeyUp('shift')
# 'Left 키' 두 번 누르기
pyautogui.press(['left', 'left'])
# 'Ctrl 키'와 's 키' 동시에 누르기
pyautogui.hotkey('ctrl', 's')
# 그림판에서 사각형 연속으로 그리기
import pyautogui
distance = 200
while distance > 0:
# Move Right
pyautogui.drag(distance, 0, duration=0.5)
distance -= 5
# Move Down
pyautogui.drag(0, distance, duration=0.5)
# Move Left
pyautogui.drag(-distance, 0, duration=0.5)
distance -= 5
# Move Up
pyautogui.drag(0, -distance, duration=0.5)
# 마우스 클릭 및 드래그
import pyautogui, time
# 버튼 누르기
pyautogui.moveTo(-2838, 96)
pyautogui.click()
time.sleep(2)
# 영역 선택하기
pyautogui.moveTo(-4994, 546)
pyautogui.dragTo(-2786, 1668, duration=2, button='left')
time.sleep(2)
pyautogui.mouseUp(-2786, 1668, button='left')
time.sleep(2)