Software/Automation

AutoIt 웹자동화를 위한 환경설정 및 코딩방법

juhpark 2022. 6. 1. 11:58
반응형

AutoIt를 활용한 웹자동화 방법에 대해서 설명하고자 한다. 여기서는 크롬 웹브라우져를 기본으로 진행할 예정이다. 웹자동화를 하기 이전 설치해야 될 것들을 먼저 설명하면

1. AutoIt설치 (다운로드 링크 중에 AutoIt Full Installation이라고 적힌 부분의 프로그램 다운로드 후 설치)

 

AutoIt Downloads - AutoIt

You can download the main AutoIt package and other related scripting tools from this page.

www.autoitscript.com

 

 

2. 크롬 드라이버는 현재 설치된 크롬버전과 맞는 버전을 다운로드 받아 설치하도록 한다. 크롬이 업데이트 되어 버전이 다른게 되면 매번 크롬 드라이버를 업데이트 해야 하는 불편함이 있긴 하다.  크롬드라이버 실행화일은 autoit 실행스크립트의 디렉토리에 함께 넣어서 실행하는 것이 편리하다.

 

ChromeDriver - WebDriver for Chrome - Downloads

Current Releases If you are using Chrome version 103, please download ChromeDriver 103.0.5060.24 If you are using Chrome version 102, please download ChromeDriver 102.0.5005.61 If you are using Chrome version 101, please download ChromeDriver 101.0.4951.41

chromedriver.chromium.org

 

3. 웹드라이버 관련 모듈을 다운로드 받는다. 다운받은 파일은 AutoIt3 설치 디렉토리의 include 폴더에 넣어준다. 확장자가 au3인 파일들을 넣어주면 된다.

 

WebDriver - AutoIt Wiki

The W3C WebDriver API is a platform and language-neutral interface and wire protocol allowing programs or scripts to control the behavior of a web browser. Introduction WebDriver API WebDriver enables developers to create automated tests that simulate user

www.autoitscript.com

 

4. 웹자동화 또는 테스팅을 위한 작업을 해보자

제일 먼저 필요한 라이브러리들을 추가한다.

#include <MsgBoxConstants.au3>
#include "wd_capabilities.au3"
#include "wd_helper.au3"

 

그리고, 환경설정이 필요한데, Capabilities라고 불리우는 문자열을 사용하는데, 형식은 다음과 같다.

#크롬
{"capabilities": {"alwaysMatch": {"goog:chromeOptions": {"w3c": true, "excludeSwitches": [ "enable-automation"]}}}}

#엣지
{"capabilities": {"alwaysMatch": {"ms:edgeOptions": {"excludeSwitches": [ "enable-automation"]}}}}

 

위와 같은 문자열을 쉽게 만들기 위해 wd_capabilites.au3 모듈을 제공한다. 아래와 같이 입력을 하면, $sCapabilites 변수에 위의 스트링이 저장된다.

#크롬
_WD_CapabilitiesStartup()
_WD_CapabilitiesAdd("alwaysMatch", "chrome")
_WD_CapabilitiesAdd("w3c", True)
_WD_CapabilitiesAdd("excludeSwitches", "enable-automation")
Local $sCapabilities = _WD_CapabilitiesGet()

#엣지
_WD_CapabilitiesStartup()
_WD_CapabilitiesAdd("alwaysMatch", "edge")
_WD_CapabilitiesAdd("excludeSwitches", "enable-automation")
Local $sCapabilities = _WD_CapabilitiesGet()

 

그 다음 WebDriver 옵션을 지정한다. 다운받은 webdriver의 위치, 포트, 타임아웃, 로그패스등을 지정하게 된다. @ScriptDir은 실행 스크립트가 있는 디렉토리를 의미한다. Chr(34)는 "(double-quotation)을 의미한다.

; setting WebDriver options
_WD_Option("Driver", @ScriptDir & "\chromedriver.exe")
_WD_Option("Port", 9515)
_WD_Option("DefaultTimeout", 1000)
_WD_Option("DriverParams", "--log-path=" & Chr(34) & @ScriptDir & "\WebDriver_Testing.log" & Chr(34))

 

그 다음은 실제 웹드라이브를 실행하고 세션을 연결한 뒤, 세션을 종료하고, 웹드라이브를 종료하는 절차를 보여준다.

; 웹드라이브 시작
_WD_Startup()
If @error Then Return SetError(@error, @extended, "")
; 콘솔 창을 보려면 true로 변경
_WD_ConsoleVisible(false)

; 세션생성 - 웹드라이브 프로세스에 접속
Local $WD_SESSION = _WD_CreateSession($sCapabilities)
If @error Then Return SetError(@error, @extended, $WD_SESSION)

; 스크립트로 실행되는 경우 MsgBox로 정보출력, 컴파일된 exe파일에서 실행되는 경우, 스킵
If Not @Compiled Then MsgBox($MB_OK + $MB_TOPMOST + $MB_ICONINFORMATION, "Information #" & @ScriptLineNumber, "Waiting before _WD_Shutdown()")

; 자동화 스크립트 작성 부분

; 세션종료 - 웹드라이브 프로세스 접속종료
_WD_DeleteSession($WD_SESSION)

; 웹드라이브 종료(셧다운)
_WD_Shutdown()

 

위 소스에서 자동화 스크립트 작성부분에 실제 원하는 웹사이트로 이동하거나 원하는 링크를 클릭하는 등의 자동화 작업을 진행할 수 있다. 객체를 찾을 때는 ID, Name, XPath를 사용해서 찾을 수 있고, XPath는 크롬의 검사도구에서 복사를 하면 쉽게 찾을 수 있다.

; 윈도우 창의 크기를 최대화하여 화면크기에 맞춘다
_WD_Window($WD_SESSION, "MAXIMIZE")

; 원하는 페이지로 이동한다.
_WD_Navigate($WD_SESSION, "http://www.google.co.kr")

; name으로 input객체를 검색한 뒤, 검색어를 입력
$obj = _WD_GetElementByName($WD_SESSION,"q")
_WD_SetElementValue($WD_SESSION,$obj,"juhpark tistory")
	
; 검색버튼을 XPath를 사용해서 찾은 뒤,버튼을 클릭함
$obj = _WD_FindElement($WD_SESSION,$_WD_LOCATOR_ByXPath, "/html/body/div[1]/div[3]/form/div[1]/div[1]/div[3]/center/input[1]")
_WD_ElementAction($WD_SESSION,$obj, "CLICK")

; 3초간 대기
_WD_LoadWait($WD_SESSION, 3000)

 

아래는 위에서 설명한 내용의 전체 실행이 가능한 소스이다.

#include <MsgBoxConstants.au3>
#include "wd_capabilities.au3"
#include "wd_helper.au3"

_WD_CapabilitiesStartup()
_WD_CapabilitiesAdd("AlwaysMatch")
_WD_CapabilitiesAdd("acceptInsecureCerts", True)
_WD_CapabilitiesAdd("firstMatch", "chrome")
_WD_CapabilitiesAdd("w3c", True)
_WD_CapabilitiesAdd("prefs", "download.defult_directory", @ScriptDir & "\Downloads")
_WD_CapabilitiesAdd("excludeSwitches", "enable-automation")
_WD_CapabilitiesDump(@ScriptLineNumber & " Testing")
Local $sCapabilities = _WD_CapabilitiesGet()


_WD_Option("Driver", @ScriptDir & "\chromedriver.exe")
_WD_Option("Port"  , 9515)
_WD_Option("DefaultTimeout", 1000)
_WD_Option("DriverParams", "--log-path=" & Chr(34) & @ScriptDir & "\WebDriver_Testing.log" & Chr(34))

_WD_Startup()
_WD_ConsoleVisible(false);

Local $WD_SESSION = _WD_CreateSession($sCapabilities)

_WD_Window($WD_SESSION, "MAXIMIZE")

_WD_Navigate($WD_SESSION, "http://www.google.co.kr")

$obj = _WD_GetElementByName($WD_SESSION,"q")
_WD_SetElementValue($WD_SESSION,$obj,"juhpark tistory")

$obj = _WD_FindElement($WD_SESSION,$_WD_LOCATOR_ByXPath, "/html/body/div[1]/div[3]/form/div[1]/div[1]/div[3]/center/input[1]")
_WD_ElementAction($WD_SESSION,$obj, "CLICK")


_WD_LoadWait($WD_SESSION, 3000)

If Not @Compiled Then MsgBox($MB_OK + $MB_TOPMOST + $MB_ICONINFORMATION, "Information #" & @ScriptLineNumber, "Waiting before _WD_Shutdown()")


_WD_DeleteSession($WD_SESSION)
_WD_Shutdown()

 

'Software > Automation' 카테고리의 다른 글

윈도우용 자동화 도구 - AutoIT소개  (0) 2022.03.29