LoginSignup
16
27

More than 5 years have passed since last update.

PowerShellでWebサイトの入力項目をname属性で操作する

Posted at

はじめに

Webブラウザに入力する作業を自動化したい!!
でも、端末にSeleniumDriverインストールできない。
という環境で、PowerShellを利用して自動化を実現しました。

やりたいこと

  1. 所定のWebサイトを開く。
  2. IDとパスワードを入力する。
  3. ボタンを押す。

環境

  • Windows7
  • Internet Explorer11
  • PowerShell2.0

操作対象Webサイト

操作対象のWebサイト(sample1.html)は、IDとパスワードと画面遷移用のボタンがあるシンプルな構成です。
ただ、すべてのタグにID属性が付いていません…

sample1.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>PowerShellからWebサイト操作</title>
    </head>
    <body>
        <form name="auth" method="post" action="./sample2.html">
            認証ID:<input type="text" name="auth_id" value=""><br>
            認証パスワード:<input type="password" name="auth_password" value=""><br>
            <input type="submit" value="認証">
        </form>
    </body>
</html>

PowerShellコード

Webサイトを操作するためのPowerShellのコードです。
ポイントは、getElementsByNameで取得したオブジェクトは配列としてアクセスしなければならない点です。
ID属性があれば、getElementByIdでオブジェクト取得できます。

sample.ps1
# Internet Explorerを起動する。
$ie = New-Object -ComObject InternetExplorer.Application

# Internet Explorerを表示する。
$ie.Visible = $true

# Web画面へ移動する。
$ie.Navigate('.\sample1.html')

# ページが完全に切り替わるのを待つ。
while($ie.Busy) { Start-Sleep -milliseconds 100 }

# IE画面操作を行うためのドキュメントオブジェクト取得
$doc = $ie.document

# ID入力
$idElements = $doc.getElementsByName("auth_id")
# idElementsは複数取得されるので、1つしか要素がなくとも配列としてアクセスする必要がある
@($idElements)[0].value = "あいでぃ"

# パスワード入力
$passwdElements = $doc.getElementsByName("auth_password")
@($passwdElements)[0].value = "パスワード"

# ボタンクリック(IDもNameもないので、valueで判定)
$inputElements = $doc.getElementsByTagName("input")
Foreach($inputElement in $inputElements) {
    if ($inputElement.value -eq "認証") {
        $inputElement.click()
    }
}

おわりに

今回はじめてPowerShell周りを調べてみたのですが、色々できて楽しいですね。
Windows10からはBash on WindowsでBash書けるようになるようですので、単純な繰り返し作業はどんどんShellScript化していきたいです。

参考サイト

16
27
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
16
27