uezo / TinySeleniumVBA

A tiny Selenium wrapper written in pure VBA
MIT License
60 stars 17 forks source link

Add Method. SaveScreenShot #19

Open ghost opened 3 years ago

ghost commented 3 years ago

スクリーンショットを取得して指定フォルダに保存するメソッドです。

WebDriver.cls

' Save Screenshot               '2021/8/14 add ishi
Public Sub SaveScreenshot(filename As String, _
                          Optional ElementId As String = vbNullString, _
                          Optional ByVal sessionid As String = vbNullString)
    Dim data As New Dictionary
    If sessionid <> vbNullString Then
        data.Add "sessionId", sessionid
    End If

    Dim png As String
    If ElementId = vbNullString Then
        png = Execute(CMD_SCREENSHOT, data)
    Else
        data.Add "id", ElementId
        png = Execute(CMD_ELEMENT_SCREENSHOT, data)
    End If

    ' Conversion from base64 string to Byte array
    Dim chars() As Byte
    With CreateObject("MSXML2.DOMDocument").createElement("b64")
        .dataType = "bin.base64"
        .text = png
        chars = .nodeTypedValue
    End With

    ' png file put
    Dim fp As Long
    fp = FreeFile
    Open filename For Output As fp
    Close fp
    Open filename For Binary Access Write As fp
        Put #fp, 1, chars
    Close fp
End Sub

WebElement.cls

' Save Screenshot                   '2021/8/14 add ishi
Public Sub SaveScreenshot(filename As String)
    Driver_.SaveScreenshot filename, ElementId_, SessionId_
End Sub

=========================================================== 動作確認

    'Save Screenshot
    objDrv.SaveScreenshot Application.ThisWorkbook.path & "\" & "Screenshot1.png"

    'Save Element Screenshot
    Set objElm = objDrv.FindElement(By.CssSelector, < ElementのSelector値 > )
    objElm.SaveScreenshot Application.ThisWorkbook.path & "\" & "Screenshot2.png"