vba:: SeleniumVBA 설치와 기본예제 (Not SeleniumBasic)

 

엑셀에서 VBA를 활용해 브라우저를 컨트롤 하는 "셀레니움-베이직"(https://github.com/florentbr/SeleniumBasic)을 많이들 사용합니다.

 

지금으로 부터 9년전에 업데이트가 있은 뒤, 더 이상 개발은 진행되고 있지 않습니다. 사용하는데 문제는 없지만 오래된 dotnet framework v3.5 환경에서 빌드되다보니 설치-실행이전에는 꼭 framwork v3.5를 설치해야 하는 번거로움이 있습니다.

 

이와 유사하지만 "셀레니움VBA (SeleniumVBA)"가 있어서 한번 설치를 해보겠습니다.

Github 소스코드 관리자 3명 중에는 VBA 코드 관련 툴인 RubberVBA의 주요개발자의 이름이 보입니다.

그래서 신뢰가 가기도 합니다.

 

 

 

설치 및 다운로드

 

https://github.com/GCuser99/SeleniumVBA

위 설치파일을 다운받은 Setup.exe를 더블클릭해서 설치합니다.

인터넷에서 다운받은 exe파일은 파란색 안내창이 뜨기도 하지만 실행을 진행하면 문제가 없습니다.

 

 

위 그림에서도 보이는 SeleniumVBA.xlsm 파일을 통해 예제를 실행해 볼 수도 있습니다.

SeleniumVBA.xlsm
0.53MB

 

 

 

 

엑셀을 실행합니다. 그리고 ALT + F11키를 통해 VBE로 들어갑니다.

Tools >> Reference 메뉴로 들어갑니다.

 

 

 

Reference(참조) 항목에서 "SeleniumVBA"를 선택합니다.

 

 

 

 

아래 SeleniumVBA 홈페이지에서 소개하는 기본 예제코드를 붙여 넣습니다.

그리고 실행(F5)키를 눌러 테스트합니다.

 

Sub doSendKeys()
    Dim driver As New WebDriver
    Dim keys As New WebKeyboard
    
    driver.StartChrome
    driver.OpenBrowser
    
    driver.NavigateTo "https://www.google.com/"
    driver.Wait 1000
    
    keySeq = "This is COOKL!" & keys.Repeat(keys.LeftKey, 3) & keys.DeleteKey & keys.ReturnKey
    
    driver.FindElement(By.Name, "q").SendKeys keySeq
    driver.Wait 2000
    
    driver.CloseBrowser
    driver.Shutdown
End Sub

 

 

 

테스트를 하면 아래처럼 구글창이 자동으로 펼쳐졌다가 2초 정도 시간이 지난 뒤 자동으로 닫히는 과정이 진행됩니다.

 

 

 

 

 

 

 

호환되는 버전은 2007이전 버전이 아니면 대부분 지원되어 크게 사용하는데 문제가 없을 듯 합니다.

 

 

 

 

 

참고사이트

 

추가 상세한 자료는 아래 홈페이지 설명을 참고하면 됩니다.

 

https://github.com/GCuser99/SeleniumVBA/wiki

 

Home

A comprehensive Selenium wrapper for browser automation developed for MS Office VBA running in Windows - GCuser99/SeleniumVBA

github.com

 

 

 

 

 

 

참고예제

 

Sub TestSeleniumVBA()
    Dim driver As New WebDriver
    Dim keys As New WebKeyboard
    Dim element As WebElement
    Dim actions As WebActionChain
    
    ' Chrome 브라우저 시작
    driver.StartChrome
    driver.OpenBrowser
    
    ' 웹사이트로 이동
    driver.NavigateTo "https://www.google.com"
    driver.Wait 1000 ' 1초 대기
    
    ' 검색창 찾아서 텍스트 입력
    Set element = driver.FindElement(By.Name, "q")
    element.SendKeys "SeleniumVBA GitHub" & keys.ReturnKey
    driver.Wait 2000
    
    ' ActionChain을 사용한 마우스 동작
    Set actions = driver.ActionChain
    Set element = driver.FindElement(By.TagName, "body")
    actions.SendKeys(keys.PageDownKey).Perform
    driver.Wait 1000
    
    ' 새 탭 열기
    Dim newWindow As WebWindow
    Set newWindow = driver.Windows.SwitchToNew(windowType:=svbaTab)
    driver.NavigateTo "https://github.com/GCuser99/SeleniumVBA"
    driver.Wait 2000
    
    ' 원래 탭으로 돌아가기
    driver.Windows.SwitchToByTitle "SeleniumVBA GitHub - Google 검색"
    driver.Wait 1000
    
    ' 브라우저 창 최대화
    driver.ActiveWindow.Maximize
    driver.Wait 1000
    
    ' 브라우저 닫기
    driver.CloseBrowser
    driver.Shutdown
End Sub

 

 

 

 

 

bbc korea 뉴스사이트의 제목을 크롤링하기

Sub GetBBCKoreanNews()
    Dim driver As New WebDriver
    Dim elements As WebElements
    Dim element As WebElement
    Dim row As Long
    
    ' 크롬 드라이버 시작
    driver.StartChrome
    driver.OpenBrowser
    
    ' BBC 한국어 페이지로 이동
    driver.NavigateTo "https://www.bbc.com/korean"
    driver.Wait 3000 ' 페이지 로딩 대기
    
    ' bbc-ugjnjh 클래스를 가진 요소들 찾기
    Set elements = driver.FindElements(By.CssSelector, ".bbc-ugjnjh")
    
    ' 시작 행 설정
    row = 1
    
    ' 각 제목을 엑셀에 입력
    For Each element In elements
        If Len(Trim(element.GetText)) > 0 Then
            Debug.Print element.GetText  ' 디버그 창에서 확인
            ThisWorkbook.Sheets(1).Cells(row, 1).Value = element.GetText
            row = row + 1
        End If
    Next element
    
    ' 브라우저 종료
    driver.CloseBrowser
    driver.Shutdown
    
    MsgBox "뉴스 제목 수집 완료. 총 " & (row - 1) & "개의 제목이 수집되었습니다.", vbInformation
End Sub

 

 

 

 

 

 

 

https://blog.naver.com/hijig35/222173127235

 

VBA 사용기 3편(Chrome with Selenium)

크롬 사용기 - 성공 / 매우 만족 VBA에서 익스플로러를 제어하기 위해서는 엑셀만 있으면 따로 프로그램...

blog.naver.com

(따라하기 미완성...)

Sub test()
    Dim driver As New WebDriver
    Dim element As WebElement
    Dim nTotalCnt As Long, nCnt As Long
    Dim strURL As String, timeText As String, nameText As String, linkHref As String
    
    strURL = "https://shoppinglive.naver.com/calendar?d=21"
    
    driver.StartChrome
    driver.OpenBrowser
    
    driver.NavigateTo strURL
    driver.Wait 1000
    
    nTotalCnt = 0
    
    ' Handle dynamic loading by scrolling until all content is loaded
    Dim i As Long
    For i = 1 To 100
        driver.ExecuteScript "window.scrollTo(0, 99999);"
        driver.Wait 1000
        
        ' Check if all items are loaded
        If nTotalCnt = driver.FindElements(By.ClassName, "VideoDate_time_t7ukR").Count Then
            Exit For
        End If
        nTotalCnt = driver.FindElements(By.ClassName, "VideoDate_time_t7ukR").Count
    Next i
    
    ' Write total count to Excel
    Range("C1") = "총 " & nTotalCnt & "건"
    
    nCnt = 1
    
    ' Extract information and write to Excel
    Dim elements As WebElements
    Set elements = driver.FindElements(By.ClassName, "VideoDate_time_t7ukR")
    
    For Each element In elements
        ' Extract time, name, and link using XPath
        timeText = element.FindElement(By.XPath, "./a/div/time").GetText
        nameText = element.FindElement(By.XPath, "./a/span").GetText
        linkHref = element.FindElement(By.XPath, "./a").GetAttribute("href")
        
        ' Write to Excel cells
        Range("A" & nCnt + 1) = timeText
        Range("B" & nCnt + 1) = nameText
        Range("C" & nCnt + 1) = linkHref
        
        nCnt = nCnt + 1
    Next element
    
    driver.CloseBrowser
    driver.Shutdown
    
    Set driver = Nothing
End Sub

 

 

 

 

 

 

 

_

반응형