0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Webブラウザ(Microsoft Edge や Google Chrome など)を Selenium で自動操作する VBScript

Posted at

[事前準備]

  1. .Net Framework 3.5 をインストール(もしくは[有効]に)する
  2. SeleniumBasic を([C:\Program Files]以外の管理者権限のいらないフォルダに)インストールする
  3. 使用中の Edge(または Chrome)と同じバージョンの Webドライバをダウンロードする
  4. ダウンロードした Webドライバを SeleniumBasic をインストールしたフォルダにコピーする
    msedgedriver.exe は、ファイル名を edgedriver.exe に変更する

<補足>
使用中の Edge(または Chrome)のバージョンが更新された場合は、
SeleniumBasic フォルダの Webドライバも同じバージョンに更新する

BrowserBySelenium.vbs
Option Explicit

Dim drv  '// --[1]
Call OpenDrv("https://www.web-site.ne.jp/")
Call WaitName("userId"):    '// userIdボックスを読み込むまで待つ
With drv
    .Wait 200   '// 念のためにさらに0.2秒待つ
    With .FindElementByName("userId")
        .Clear
        .SendKeys "user"
    End With
    With .FindElementByName("password")
        .Clear
        .SendKeys "hoge"
    End With
    .FindElementById("login-link").Click
    .Window.Maximize    '// ウィンドウを最大化する
End With
WScript.Sleep 1200000   '// 20分後に終了 --[2]
'// URLを Edge(Chrome)で開く
Sub OpenDrv(url)
    Set drv = CreateObject("Selenium.WebDriver")
    With drv
        .start "Edge"
        '.start "Chrome"
        .Get url
    End With
End Sub
'// name属性(name_value)の要素を読み込むまで待つ
Sub WaitName(ByVal name_value)
    Dim t, xBy, isElm
    Set xBy = CreateObject("Selenium.By")
    Do Until isElm
        isElm = drv.IsElementPresent(xBy.Name(name_value))
        drv.Wait 200
        t = t + 200
        If t > 20000 Then
            MsgBox "ブラウザの応答がありません。name_value:" & name_value
            WScript.Quit
        End If
    Loop
End Sub
'// リンク(link_txt)を読み込むまで待つ
Sub WaitLink(ByVal link_txt)
    Dim t, xBy, isElm
    Set xBy = CreateObject("Selenium.By")
    Do Until isElm
        isElm = drv.IsElementPresent(xBy.partiallinktext(link_txt))
        drv.Wait 200
        t = t + 200
        If t > 20000 Then
            MsgBox "ブラウザの応答がありません。link_txt:" & link_txt
            WScript.Quit
        End If
    Loop
End Sub
'// チェックボックスの OnOff を切り替える
Sub CheckBoxOnOff(ByVal element_name, ByVal on_off)
    on_off = False
    With drv.FindElementByName(element_name)
        If on_off Then
            If Not .IsSelected Then .Click
        Else
            If .IsSelected Then .Click
        End If
    End With
End Sub

ポイントは、
[1]Selenium.WebDriver オブジェクトはグローバル変数(drv)に入れる
[2]スクリプトの終了と同時にブラウザのウィンドウも閉じてしまうので、
WScript.Sleepで待機させてスクリプトを実行中のままにしておく(苦肉の策:sweat_drops:
:scream:な画面も時間が過ぎたら勝手に閉じてくれるので何気に便利:hearts:

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?