Webページでは何かを選択する際にラジオボタンのUIが使われることも多い。今回はPowerShellからこのラジオボタンを操作する方法について取り上げる。

→連載「PowerShell Core入門 - 基本コマンドの使い方」の過去回はこちらを参照。

ラジオボタンを操作する

今回サンプルとして使うサイトも前回と同じ「Checkout example · Bootstrap v5.0」だ。

  • Checkout example · Bootstrap v5.0

    Checkout example · Bootstrap v5.0

  • Checkout example · Bootstrap v5.0の下の方にあるラジオボタンを使う

    Checkout example · Bootstrap v5.0の下の方にあるラジオボタンを使う

前回と同じようにMicrosoft Edgeの開発者ツールを開いて(メニュー「その他のツール」→「開発者ツール」または「Ctrl」+「Shift」+「I」)、ラジオボタンのXPathを調べておく。

  • Microsoft Edgeの開発者ツールでラジオボタンのXPathを調べる

    Microsoft Edgeの開発者ツールでラジオボタンのXPathを調べる

要素 XPath
Credit card //∗[@id="credit"]
Debit card //∗[@id="debit"]
PayPal //∗[@id="paypal"]

ラジオボタンのクリック操作まとめ

ラジオボタンのクリック操作については前回取り上げているので、その内容を次にまとめておく。

◆Microsoft Edge WebDriverの起動とサンプルページのオープン

PS C:\Users\daichi> webdriver_edge_start.ps1
Microsoft Edge WebDriverを起動します。
Microsoft Edge WebDriverの起動処理完了。
PS C:\Users\daichi> Set-SeUrl -Url https://getbootstrap.jp/docs/5.0/examples/checkout/
PS C:\Users\daichi>

◆1つ目のラジオボタンをクリック

PS C:\Users\daichi> $Element = Get-SeElement -By XPath -Value '//*[@id="credit"]'
PS C:\Users\daichi> Invoke-SeClick -Element $Element -Action Click
PS C:\Users\daichi>
  • 1つ目のラジオボタンをクリックした結果

    1つ目のラジオボタンをクリックした結果

◆2つ目のラジオボタンをクリック

PS C:\Users\daichi> $Element = Get-SeElement -By XPath -Value '//*[@id="debit"]'
PS C:\Users\daichi> Invoke-SeClick -Element $Element -Action Click
PS C:\Users\daichi>
  • 2つ目のラジオボタンをクリックした結果

    2つ目のラジオボタンをクリックした結果

◆3つ目のラジオボタンをクリック

PS C:\Users\daichi> $Element = Get-SeElement -By XPath -Value '//*[@id="paypal"]'
PS C:\Users\daichi> Invoke-SeClick -Element $Element -Action Click
PS C:\Users\daichi>
  • 3つ目のラジオボタンをクリックした結果

    3つ目のラジオボタンをクリックした結果

◆Microsoft EdgeとWebDriverの終了

PS C:\Users\daichi> webdriver_edge_stop.ps1
動作しているMicrosoft Edge WebDriverを終了します。

 NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
 ------    -----      -----     ------      --  -- -----------
     23     8.14      23.81       0.03   18164   5 msedgedriver
動作しているMicrosoft Edge WebDriverの終了処理完了。

PS C:\Users\daichi>

Microsoft Edge WebDriverの起動と終了に使ったPowerShellスクリプトは稿末に掲載しておくので、そちらをご参照いただければと思う。

ラジオボタンはグループで使うもの

ラジオボタンは単一で使われることはなく、複数のラジオボタンでグループ化して使われる。サンプルページのラジオボタン部分を調べてみる。

  • ラジオボタン周辺のHTML

    ラジオボタン周辺のHTML

それぞれのラジオボタンは次のような要素として記述されている。

◆1つ目のラジオボタンを表すinput要素

<input id="credit" name="paymentMethod" type="radio" class="form-check-input" checked required>

◆2つ目のラジオボタンを表すinput要素

<input id="debit" name="paymentMethod" type="radio" class="form-check-input" required>

◆3つ目のラジオボタンを表すinput要素

<input id="paypal" name="paymentMethod" type="radio" class="form-check-input" required>

「name="paymentMethod"」という記述に注目だ。この属性がグルーピングの対象となっており、あるラジオボタンを選択すると、同じグループに所属している(同じname属性が指定されている)ラジオボタンの選択が解除される。グループの中で常に1つだけ選択されている、それがラジオボタンだ。

このようなボタンになっている場合、逆に現在どのボタンが選択されているのかをPowerShell側から知る必要が出てくることがある。今回はこの情報を得る方法を説明する。

要素オブジェクトが情報を持っている

Get-SeElementコマンドレットで対象となるラジオボタンを取得しているわけだが、実はこの取得したものにすでに選択の有無といった情報が含まれている。Get-SeElementコマンドレットで要素を取得したあとで、Get-Memberコマンドレットを使ってプロパティを調べてみるとそれがよくわかる。

PS C:\Users\daichi> $Element = Get-SeElement -By XPath -Value '//*[@id="paypal"]'
PS C:\Users\daichi> $Element | Get-Member

   TypeName: OpenQA.Selenium.Remote.RemoteWebElement

Name                                 MemberType Definition
----                                 ---------- ----------
Clear                                Method     void Clear(), void IWebElement.Clear()
Click                                Method     void Click(), void IWebElement.Click()
Equals                               Method     bool Equals(System.Object obj)
FindElement                          Method     OpenQA.Selenium.IWebElement FindElement(OpenQA.Selenium.By by), OpenQA…
FindElementByClassName               Method     OpenQA.Selenium.IWebElement FindElementByClassName(string className), …
FindElementByCssSelector             Method     OpenQA.Selenium.IWebElement FindElementByCssSelector(string cssSelecto…
FindElementById                      Method     OpenQA.Selenium.IWebElement FindElementById(string id), OpenQA.Seleniu…
FindElementByLinkText                Method     OpenQA.Selenium.IWebElement FindElementByLinkText(string linkText), Op…
FindElementByName                    Method     OpenQA.Selenium.IWebElement FindElementByName(string name), OpenQA.Sel…
FindElementByPartialLinkText         Method     OpenQA.Selenium.IWebElement FindElementByPartialLinkText(string partia…
FindElementByTagName                 Method     OpenQA.Selenium.IWebElement FindElementByTagName(string tagName), Open…
FindElementByXPath                   Method     OpenQA.Selenium.IWebElement FindElementByXPath(string xpath), OpenQA.S…
FindElements                         Method     System.Collections.ObjectModel.ReadOnlyCollection[OpenQA.Selenium.IWeb…
FindElementsByClassName              Method     System.Collections.ObjectModel.ReadOnlyCollection[OpenQA.Selenium.IWeb…
FindElementsByCssSelector            Method     System.Collections.ObjectModel.ReadOnlyCollection[OpenQA.Selenium.IWeb…
FindElementsById                     Method     System.Collections.ObjectModel.ReadOnlyCollection[OpenQA.Selenium.IWeb…
FindElementsByLinkText               Method     System.Collections.ObjectModel.ReadOnlyCollection[OpenQA.Selenium.IWeb…
FindElementsByName                   Method     System.Collections.ObjectModel.ReadOnlyCollection[OpenQA.Selenium.IWeb…
FindElementsByPartialLinkText        Method     System.Collections.ObjectModel.ReadOnlyCollection[OpenQA.Selenium.IWeb…
FindElementsByTagName                Method     System.Collections.ObjectModel.ReadOnlyCollection[OpenQA.Selenium.IWeb…
FindElementsByXPath                  Method     System.Collections.ObjectModel.ReadOnlyCollection[OpenQA.Selenium.IWeb…
GetAttribute                         Method     string GetAttribute(string attributeName), string IWebElement.GetAttri…
GetCssValue                          Method     string GetCssValue(string propertyName), string IWebElement.GetCssValu…
GetHashCode                          Method     int GetHashCode()
GetProperty                          Method     string GetProperty(string propertyName), string IWebElement.GetPropert…
GetScreenshot                        Method     OpenQA.Selenium.Screenshot GetScreenshot(), OpenQA.Selenium.Screenshot…
GetType                              Method     type GetType()
SendKeys                             Method     void SendKeys(string text), void IWebElement.SendKeys(string text)
Submit                               Method     void Submit(), void IWebElement.Submit()
ToString                             Method     string ToString()
Coordinates                          Property   OpenQA.Selenium.Interactions.Internal.ICoordinates Coordinates {get;}
Displayed                            Property   bool Displayed {get;}
Enabled                              Property   bool Enabled {get;}
Location                             Property   System.Drawing.Point Location {get;}
LocationOnScreenOnceScrolledIntoView Property   System.Drawing.Point LocationOnScreenOnceScrolledIntoView {get;}
Selected                             Property   bool Selected {get;}
Size                                 Property   System.Drawing.Size Size {get;}
TagName                              Property   string TagName {get;}
Text                                 Property   string Text {get;}
WrappedDriver                        Property   OpenQA.Selenium.IWebDriver WrappedDriver {get;}

PS C:\Users\daichi>

プロパティの1つに、論理値の「Selected」がある。これが今回目的とするデータだ。

それぞれのラジオボタンを取得してSelectedプロパティの値を表示させると次のようになる。

◆1つ目のラジオボタンが選択されているかどうかを確認

PS C:\Users\daichi> $Element = Get-SeElement -By XPath -Value '//*[@id="credit"]'
PS C:\Users\daichi> $Element.Selected
False
PS C:\Users\daichi>

◆2つ目のラジオボタンが選択されているかどうかを確認

PS C:\Users\daichi> $Element = Get-SeElement -By XPath -Value '//*[@id="debit"]'
PS C:\Users\daichi> $Element.Selected
False
PS C:\Users\daichi>

◆3つ目のラジオボタンが選択されているかどうかを確認

PS C:\Users\daichi> $Element = Get-SeElement -By XPath -Value '//*[@id="paypal"]'
PS C:\Users\daichi> $Element.Selected
True
PS C:\Users\daichi>

ここでは3つ目のラジオボタンが選択されている状態なので、その状態通りに値が取得できていることがわかる。

チェックボックスも選択の状態を調べることができる

選択されているかどうかは前回取り上げたチェックボックスでも同じだ。Selectedプロパティを調べると選択されているかどうかがわかる。チェックボックスが最初から選択されているのか選択されていないのか不明な場合は、まずこのプロパティの値を調べてからクリックするかどうかを選択するといったことを行うことになる。

こんな感じで、PowerShell Seleniumでは操作をするだけではなく状態を取得することができる。Webページの表示内容に合わせて操作内容を変えるといったことができるわけだ。

付録

webdriver_edge_start.ps1

#!/usr/bin/env pwsh

#========================================================================
# Microsoft Edge WebDriverを起動する
#========================================================================

#========================================================================
# 動作しているMicrosoft Edge WebDriverをすべて終了
#========================================================================
webdriver_edge_stop.ps1

#========================================================================
# Seleniumモジュールがない場合にはインストール
#========================================================================
if (-Not (Get-InstalledModule -Name Selenium 2> $Null)) {
    'Seleniumモジュールをインストールします。'
    Install-Module -Name Selenium -AllowPrerelease -Force
    Get-InstalledModule -Name Selenium
}

#========================================================================
# Microsoft Edge WebDriverを起動
#========================================================================
'Microsoft Edge WebDriverを起動します。'
$Size = '1200,800'
if  (-Not (Start-SeDriver -Browser Edge -Size $Size 2> $Null 3> $Null))
{
    #================================================================
    # Microsoft EdgeとMicrosoft Edge WebDriverのバージョンが一致して
    # いないためにドライバが動作しなかった可能性がある。
    #================================================================

    #================================================================
    # 不要なドライバプロセスを終了
    #================================================================
    webdriver_edge_stop.ps1

    #================================================================
    # Microsoft Edgeのバージョン番号
    #================================================================
    $EdgeDir='C:\Program Files (x86)\Microsoft\Edge\Application\'
    $EdgeVersion=(  Get-ChildItem -Name $EdgeDir                    | 
                    Where-Object { $_ -NotMatch "[a-zA-Z]+" }       )

    #================================================================
    # Microsoft Edge WebDriverダウンロードURLとデプロイ先パス
    #================================================================
    $DriverURL="https://msedgedriver.azureedge.net/$EdgeVersion/edgedriver_win64.zip"

    $SeModVer=(Get-InstalledModule -Name Selenium).Version -replace "-.+$",""
    $DriverDir="$env:HOME\Documents\powershell\Modules\Selenium\$SeModVer\assemblies"
    $DriverDownloadDir="$DriverDir\_download"

    #================================================================
    # WebDriverダウンロード用の一時ディレクトリを作成
    #================================================================
    New-Item        $DriverDownloadDir -ItemType Directory -Force

    #================================================================
    # Microsoft Edgeと同じバージョンのMicrosoft Edge WebDriverを
    # ダウンロード
    #================================================================
    "Microsoft Edge WebDriver version $EdgeVersion をダウンロードします。"
    curl            -get                                            `
                    -o      $DriverDownloadDir\edgedriver_win64.zip `
                    $DriverURL

    #================================================================
    # Microsoft Edge WebDriverをデプロイ
    #================================================================
    "Microsoft Edge WebDriver version $EdgeVersion をインストールします。"
    Expand-Archive  -Path $DriverDownloadDir\edgedriver_win64.zip   `
                    -Destination $DriverDownloadDir                 `
                    -Force

    Copy-Item       -Path $DriverDownloadDir\msedgedriver.exe       `
                    -Destination $DriverDir\msedgedriver.exe        `
                    -Force

    #================================================================
    # WebDriverダウンロード用の一時ディレクトリを削除
    #================================================================
    Remove-Item     $DriverDownloadDir -Recurse -Force

    #================================================================
    # Microsoft Edge WebDriverを起動する
    #================================================================
    if      (-Not (Start-SeDriver -Browser Edge -Size $Size 2> $Null 3> $Null)) 
    {
            #========================================================
            # 原因不明の起動不能
            #========================================================

            #========================================================
            # 不要なドライバプロセスを終了
            #========================================================
            webdriver_edge_stop.ps1

            Exit
    }
}
'Microsoft Edge WebDriverの起動処理完了。'

webdriver_edge_stop.ps1

#!/usr/bin/env pwsh

#========================================================================
# Microsoft Edge WebDriverを終了する
#========================================================================

#========================================================================
# WebDriverプロセスを終了
#========================================================================
if  (Get-Process -Name msedgedriver 2> $Null) 
{
    '動作しているMicrosoft Edge WebDriverを終了します。'
    Get-Process -Name msedgedriver 2> $Null

    # Microsoft Edge WebDriverを終了
    Stop-SeDriver 2> $Null

    # まだ動作しているほかのMicrosoft Edge WebDriverを終了
    if      (Get-Process -Name msedgedriver 2> $Null) 
    {
            Get-Process -Name msedgedriver 2> $Null | Stop-Process
    }

    '動作しているMicrosoft Edge WebDriverの終了処理完了。'
}