LoginSignup
4
1

WebDriver for Chromeの自動ダウンロード+更新

Last updated at Posted at 2022-10-21

概要

WebDriver for ChromeでRPAを利用していたら、ブラウザの自動更新が行われてしまった事で
エラーが発生してめんどくさかったのでダウンロード~更新までを自動化した。

VB.NET
Imports System.IO.Compression '参照設定 System.IO.Compression.FileSystem.dllとSystem.IO.Compression.dll
Imports Microsoft.Win32
Imports System.Net
Imports System.IO

    ''' <summary>
    ''' chromeWebDriverが古い場合はダウンロードして置き換える
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub updateChomeDriver()
        Dim zipPath As String = "C:\chrome_driver\chromedriver_win32.zip"
        Dim extractPath As String = "C:\chrome_driver"
        Dim strFileDrvVersion As String = ""

        If Not Directory.Exists(extractPath) Then
            Directory.CreateDirectory(extractPath)
        End If

        '現在インストールされているChromeブラウザバージョン取得
        Dim strChromeVer As String = GetChromeVersion()

        '現在インストールされているChromeWebDriverバージョン取得
        If IO.File.Exists(extractPath & "\chromedriver.exe") Then
            strFileDrvVersion = Runcmd("C:\chrome_driver\chromedriver.exe", "-v")
        Else
            strFileDrvVersion = ""
        End If

        '現在のChromeバージョンに見合ったDriverバージョンをサイトから調べる
        Dim siteVerURL As String = ""
        Using client As WebClient = New WebClient()
            siteVerURL = client.DownloadString("https://chromedriver.storage.googleapis.com/LATEST_RELEASE_" + strChromeVer.Substring(0, strChromeVer.LastIndexOf(".")))
        End Using

        '現在のDriverバージョンとChromeブラウザバージョンを比較する
        If strFileDrvVersion = siteVerURL Then
            '同じならば処理しない
            Exit Sub
        End If

        'カレントディレクトリ設定
        Directory.SetCurrentDirectory("C:\chrome_driver")

        'ブラウザに合ったDriverバージョンをダウンロードする
        Using wc As New WebClient
            wc.DownloadFile("https://chromedriver.storage.googleapis.com/" + siteVerURL + "/chromedriver_win32.zip", "chromedriver_win32.zip")
        End Using

        'ZIP書庫を開く
        Using z As ZipArchive = ZipFile.OpenRead(zipPath)
            Dim za As ZipArchiveEntry = z.GetEntry("chromedriver.exe")
            If za Is Nothing Then
                '見つからなかった時
                Console.WriteLine("chromedriver_win32/chromedriver.exe が見つかりませんでした。")
            Else
                '2番目の引数をTrueにすると、上書きする
                za.ExtractToFile("C:\chrome_driver\chromedriver.exe", True)
                retMsg = "ChromeDriverを" & siteVerURL & "に更新しました。"
            End If
        End Using
    End Sub


    ''' <summary>
    ''' インストールされているChromeブラウザのバージョンを取得する
    ''' </summary>
    ''' <returns>バージョン文字列</returns>
    ''' <remarks></remarks>
    Private Function GetChromeVersion() As String
        Dim wowNode As String = String.Empty
        If Environment.Is64BitOperatingSystem Then wowNode = "Wow6432Node\"
        Dim regKey As RegistryKey = Registry.LocalMachine
        Dim keyPath As RegistryKey = regKey.OpenSubKey("Software\" + wowNode + "Google\Update\Clients")

        If IsDBNull(keyPath) Then
            regKey = Registry.CurrentUser
            keyPath = regKey.OpenSubKey("Software\" + wowNode + "Google\Update\Clients")
        End If

        If IsDBNull(keyPath) Then
            regKey = Registry.LocalMachine
            keyPath = regKey.OpenSubKey("Software\Google\Update\Clients")
        End If

        If IsDBNull(keyPath) Then
            regKey = Registry.CurrentUser
            keyPath = regKey.OpenSubKey("Software\Google\Update\Clients")
        End If

        If Not IsDBNull(keyPath) Then
            Dim subKeys As String() = keyPath.GetSubKeyNames()
            For Each subKey As String In subKeys
                Dim value = keyPath.OpenSubKey(subKey).GetValue("name")
                Dim found = False

                If Not IsDBNull(value) Then
                    found = value.ToString().Equals("Google Chrome", StringComparison.InvariantCultureIgnoreCase)
                End If

                If found Then
                    Return keyPath.OpenSubKey(subKey).GetValue("pv").ToString()
                End If
            Next
        End If

        Return "NotFound"
    End Function

    ''' <summary>
    ''' コマンドプロンプトでChromeDriverのバージョンを取得する
    ''' </summary>
    ''' <param name="chromeDriverPath"></param>
    ''' <param name="strcmd"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Function Runcmd(chromeDriverPath As String, strcmd As String) As String
        'Processオブジェクト
        Dim proc As New System.Diagnostics.Process()

        With proc.StartInfo
            .FileName = chromeDriverPath

            '出力読取り可能化
            .UseShellExecute = False
            .RedirectStandardOutput = True
            .RedirectStandardInput = False

            'コマンドプロンプトのウィンドウ非表示
            .CreateNoWindow = True

            'コマンド(/c:コマンド実行後、コマンドを実行したcmd.exeを終了)
            .Arguments = "/c " & strcmd
        End With

        'コマンド実行
        proc.Start()

        '実行結果取得
        Dim result As String = proc.StandardOutput.ReadToEnd()

        proc.WaitForExit()
        proc.Close()

        Dim res As String() = result.Split(" ")

        Return res(1)

    End Function

Chromeブラウザの自動アップデート停止

ChromeDriverのLATEST_RELEASEが記載されているサイトの更新が行われなくなったので、
Chromeブラウザの自動アップデートを停止して手動対応する事にした。

【手順】

①GoogleUpdateAdmx管理用テンプレートをダウンロードする。
https://dl.google.com/update2/enterprise/googleupdateadmx.zip

②C:\Windows\PolicyDefinitionsへコピーする
解凍したgoogle.adml ファイルと GoogleUpdate.adml ファイルをC:\Windows\PolicyDefinitionsルートへコピー。
解凍したen-USフォルダの中身をC:\Windows\PolicyDefinitions\en-USフォルダへコピーする。

③コマンドプロンプトでgpedit.mscを起動する。
グループ ポリシー([コンピューターの構成] フォルダ)で次のように操作する。
[Google] ⇒ [Google Update] ⇒ [Applications] ⇒[GoogleChrome] に移動する。
[Update policy override] をオンにする。
[Options] で [Disable updates] にする。

④動作チェック
ブラウザのヘルプの[Chrome について] をクリックして、
「管理者が更新を無効にした」旨のメッセージが出ていれば効いている。

上述の手順で自動アップデートが行われなくなるので、
タイミングを見計らって手動でブラウザ更新とchromedriver.exe更新を行います。

chromeDriverの最新exeは以下のサイトに掲載されています。
https://googlechromelabs.github.io/chrome-for-testing/#stable

また、chromeブラウザの向こう3バージョンのリリースロードマップが
以下のサイトに掲載されています。
https://chromestatus.com/roadmap

4
1
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
4
1