ここでは AppleScript で Google Chrome ブラウザを操作してフォームにテキストを入力するコードを紹介します。
さてすでに以下について説明しました。(まだ読んでいない人は先にお読みください)
今回は AppleScript を使ってウェブサイトにあるフォームに情報を入力する方法です。
もくじ
AppleScript で Google Chrome ブラウザを操作してフォームにテキストを入力する
この章以降では ウェブスクレイピングの練習用のページ(フォーム入力用)をもとにして説明します。

要素の検証
STEP
名前のフォームをクリックします

STEP
そのままフォームの上で右クリックして「検証」を選択します


このコードの中身を見やすくすると以下のようになります。
<input
type="text"
id="name"
name="name">
表形式にしてみるとこんな感じ
HTMLの要素(タグ名) | input(インプット) |
type(タイプ) | text |
name(名前) | name |
id(ID または識別子) | name |
この中から HTML 要素を指定しやすいものがあるかどうか見ていきます。
- ID
- 名前
- クラス名
- タグ
id の存在が確認できますので、HTML 要素の指定には ID が簡単です。
対象のフォームにスクリプトで文字を入力する方法
ここでは名前のフォームに文字を入力してみます。
ID でフォームに文字を入力
まずは ID でフォームに文字を入力する AppleScript です。
tell application "Google Chrome"
tell front window
tell active tab
execute javascript "document.getElementById(‘name’).value=’なまえ’;"
end tell
end tell
end tell
指示した JavaScript
document.getElementById('name').value='なまえ';

名前 でフォームに文字を入力
こちらは名前でフォームに文字を入力する AppleScript です。
tell application "Google Chrome"
tell front window
tell active tab
execute javascript "document.getElementsByName(‘name’)[0].value=’なまえ‘;"
end tell
end tell
end tell
指示した JavaScript
document.getElementsByName('name')[0].value='なまえ';
JavaScript の補足
使用した JavaScript を改めて見てみましょう。
document.getElementById('name').value='なまえ';
value='なまえ'
が(いわゆる)命令です。
上記 JavaScript の前半document.getElementById('name')
で、HTML 要素を指定しました。
それに続けて命令を書くことで、その要素に対して動作を実行することができます。
