Seleniumを使ったHTML要素の操作
テキストボックスに文字を入力したりボタンをクリックするなど、HTML要素を操作する方法について説明します。
HTML要素を指定する方法については要素の指定を参照してください。
目次
クリック
ボタン/ラジオボタン/チェックボックス/リンク等をクリックする方法です。
実装方法
特定した要素に対してClickメソッドを実行します。
サンプル
'下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
Private Sub btnClick_Click(sender As Object, e As EventArgs) Handles btnClick.Click
'ボタンをクリック
_browser.FindElement(By.Id("buttonid1")).Click()
MsgBox("上記のクリックでブラウザにalertが表示されるので閉じてからOKを押す")
'ラジオボタンの2つ目をクリック
_browser.FindElements(By.Name("inputname"))(1).Click()
'チェックボックスをクリック
Dim element = _browser.FindElements(By.Name("checkname"))(0)
If element.Selected = False Then
element.Click()
End If
'リンクをクリック
_browser.FindElement(By.LinkText("リンク1")).Click()
MsgBox("上記のクリックでブラウザにalertが表示されるので閉じてからOKを押す")
End Sub
//下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
private void btnClick_Click(object sender, EventArgs e)
{
//ボタンをクリック
_browser.FindElement(By.Id("buttonid1")).Click();
MessageBox.Show("上記のクリックでブラウザにalertが表示されるので閉じてからOKを押す");
//ラジオボタンの2つ目をクリック
_browser.FindElements(By.Name("inputname"))[1].Click();
//チェックボックスをクリック
var element = _browser.FindElements(By.Name("checkname"))[0];
if (element.Selected == false) {
element.Click();
}
//リンクをクリック
_browser.FindElement(By.LinkText("リンク1")).Click();
MessageBox.Show("上記のクリックでブラウザにalertが表示されるので閉じてからOKを押す");
}
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from tkinter import messagebox
#Chromeブラウザを表示(環境変数のPATHにドライバーのパスを追加済とする)
driver = webdriver.Chrome()
#ページを表示
driver.get("https://web.biz-prog.net/test/testpage.html")
#ボタンをクリック
driver.find_element(By.ID, "buttonid1").click()
messagebox.showinfo("上記のクリックでブラウザにalertが表示されるので閉じてからOKを押す")
#ラジオボタンの2つ目をクリック
driver.find_elements(By.NAME, "inputname")[1].click()
#チェックボックスをクリック
element = driver.find_elements(By.NAME, "checkname")[0]
if element.is_selected() == False:
element.click()
#リンクをクリック
driver.find_element(By.LINK_TEXT, "リンク1").click()
messagebox.showinfo("上記のクリックでブラウザにalertが表示されるので閉じてからOKを押す")
選択
ラジオボタン/セレクトボックスを選択する方法です。
実装方法
ラジオボタン(radio)の場合は、要素を特定してからClickメソッドを実行します。
セレクトボックス(select)は少し手順が必要です。
NuGetから「Selenium.Support」をインストールしてください。
Selenium.Support.UI.SelectElementクラスを使ってselect要素の操作を行います。
サンプル
'下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
Private Sub btnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click
'ラジオボタンの2つ目を選択
_browser.FindElements(By.Name("radioname"))(1).Click()
End Sub
'下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
Private Sub btnSelectCheck_Click(sender As Object, e As EventArgs) Handles btnSelectCheck.Click
'select要素のオブジェクトを取得する
Dim selectElement = _browser.FindElement(By.Name("selectname"))
Dim selectObject = New SelectElement(selectElement)
'3番目のoption要素を選択する
selectObject.SelectByIndex(2)
MsgBox("上記によりオプションが選択された")
'option要素のvalue属性の値を指定して選択する
selectObject.SelectByValue("value1")
MsgBox("上記によりオプションが選択された")
'option要素のテキスト値を指定して選択する
selectObject.SelectByText("value2")
MsgBox("上記によりオプションが選択された")
'選択されているoption要素のオブジェクトをリストで取得する
Dim allSelectedOptions = selectObject.AllSelectedOptions
'選択されているoption要素の中で、最初のもの、またはデフォルト値になっているオブジェクトを取得する
Dim firstSelectedOption = allSelectedOptions.FirstOrDefault()
'select要素が含んでいる全てのoption要素をリストで取得する
Dim allAvailableOptions As IList(Of IWebElement) = selectObject.Options
'指定したインデックスのoption要素を選択解除する
selectObject.DeselectByIndex(1)
'option要素のvalue属性の値を指定して選択解除する
selectObject.DeselectByValue("value1")
'option要素のテキスト値を指定して選択解除する
selectObject.DeselectByText("value1")
'全てのoption要素を選択解除する
selectObject.DeselectAll()
'select要素が、複数選択可能となっているかをboolで取得する
MsgBox(selectObject.IsMultiple)
End Sub
//下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
private void btnSelect_Click(object sender, EventArgs e)
{
//ラジオボタンの2つ目を選択
_browser.FindElements(By.Name("radioname"))[1].Click();
}
//下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
private void btnSelect2_Click(object sender, EventArgs e)
{
//select要素のオブジェクトを取得する
var selectElement = _browser.FindElement(By.Name("selectname"));
var selectObject = new SelectElement(selectElement);
//3番目のoption要素を選択する
selectObject.SelectByIndex(2);
MessageBox.Show("3番目のoptionが選択された");
//option要素のvalue属性の値を指定して選択する
selectObject.SelectByValue("value1");
MessageBox.Show("1番目のoptionが選択された");
//option要素のテキスト値を指定して選択する
selectObject.SelectByText("value2");
MessageBox.Show("2番目のoptionが選択された");
//select要素(複数選択可)のオブジェクトを取得する----
selectObject = new SelectElement(_browser.FindElements(By.Name("selectname"))[1]);
//選択されているoption要素のオブジェクトをリストで取得する
var allSelectedOptions = selectObject.AllSelectedOptions;
//選択されているoption要素の中で、最初のもの、またはデフォルト値になっているオブジェクトを取得する
var firstSelectedOption = allSelectedOptions.FirstOrDefault();
//select要素が含んでいる全てのoption要素をリストで取得する
IList<IWebElement> allAvailableOptions = selectObject.Options;
//指定したインデックスのoption要素を選択解除する
selectObject.DeselectByIndex(1);
//option要素のvalue属性の値を指定して選択解除する
selectObject.DeselectByValue("value_m1");
//option要素のテキスト値を指定して選択解除する
selectObject.DeselectByText("値_m1");
//全てのoption要素を選択解除する
selectObject.DeselectAll();
//select要素が、複数選択可能となっているかをboolで取得する
MessageBox.Show(selectObject.IsMultiple.ToString());
}
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from tkinter import messagebox
from selenium.webdriver.support.select import Select
#Chromeブラウザを表示(環境変数のPATHにドライバーのパスを追加済とする)
driver = webdriver.Chrome()
#ページを表示
driver.get("https://web.biz-prog.net/test/testpage.html")
#ラジオボタンの2つ目をクリック
driver.find_elements(By.NAME, "inputname")[1].click()
#select要素を操作する場合は「from selenium.webdriver.support.select import Select」の追加が必要
#select要素のオブジェクトを取得する
selectElement = driver.find_element(By.NAME, "selectname")
selectObject = Select(selectElement)
#3番目のoption要素を選択する
selectObject.select_by_index(2)
messagebox.showinfo("3番目のoptionが選択された")
#option要素のvalue属性の値を指定して選択する
selectObject.select_by_value("value1")
messagebox.showinfo("1番目のoptionが選択された")
#option要素のテキスト値を指定して選択する
selectObject.select_by_visible_text("value2")
messagebox.showinfo("2番目のoptionが選択された")
#select要素(複数選択可)のオブジェクトを取得する
selectObject = Select(driver.find_elements(By.NAME, "selectname")[1])
#選択されているoption要素のオブジェクトをリストで取得する
allSelectedOptions = selectObject.all_selected_options
#選択されているoption要素の中で、最初のものを取得する
selectObject.select_by_index(1)
selectObject.select_by_index(2)
firstSelectedOption = selectObject.first_selected_option
#select要素が含んでいる全てのoption要素をリストで取得する
allAvailableOptions = selectObject.options
#指定したインデックスのoption要素を選択解除する
selectObject.deselect_by_index(1)
#option要素のvalue属性の値を指定して選択解除する
selectObject.deselect_by_value("value_m1")
#option要素のテキスト値を指定して選択解除する
selectObject.deselect_by_visible_text("値_m1")
#全てのoption要素を選択解除する
selectObject.deselect_all()
#select要素が、複数選択可能となっているかをboolで取得する
messagebox.showinfo(selectObject.is_multiple)
参考
入力
テキストボックスやパスワード欄に文字を入力する方法です。
実装方法
特定した要素に対してSendKeysメソッドで文字を設定します。
消す場合はClearメソッドを実行します。
サンプル
'下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
Private Sub btnSetText_Click(sender As Object, e As EventArgs) Handles btnSetText.Click
'テキストボックスに文字を入力
_browser.FindElement(By.Id("inputid2")).SendKeys("テキスト2")
'パスワードに文字を入力
_browser.FindElements(By.Name("passwordname"))(0).SendKeys("password")
End Sub
//下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
private void btnInput_Click(object sender, EventArgs e)
{
//テキストボックスに文字を入力
_browser.FindElement(By.Id("inputid2")).SendKeys("テキスト2");
//パスワードに文字を入力
_browser.FindElements(By.Name("passwordname"))[0].SendKeys("password");
}
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from tkinter import messagebox
#Chromeブラウザを表示(環境変数のPATHにドライバーのパスを追加済とする)
driver = webdriver.Chrome()
#ページを表示
driver.get("https://web.biz-prog.net/test/testpage.html")
#テキストボックスに文字を入力
driver.find_element(By.ID, "inputid2").send_keys("テキスト2")
#パスワードに文字を入力
driver.find_elements(By.NAME, "passwordname")[0].send_keys("password")
値の参照
テキストボックスに入力されている値やチェックボックスの選択状態などの、HTML要素に設定されている値を参照する方法です。
実装方法
テキストボックスの場合はGetAttributeメソッドでvalue属性の値を取得します。
ラジオボタンやチェックボックスは、要素のSelectedプロパティでtrue/falseが取得できます。
セレクトボックスはoption要素の選択状態をSelectedプロパティで取得できます。
サンプル
'下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
Private Sub btnRef_Click(sender As Object, e As EventArgs) Handles btnRef.Click
'テキストボックスを参照
MsgBox(_browser.FindElement(By.Id("inputid2")).GetAttribute("value"))
'ラジオボタンを参照
MsgBox(_browser.FindElements(By.Name("radioname"))(1).Selected)
'チェックボックスを参照
MsgBox(_browser.FindElements(By.Name("checkname"))(0).Selected)
'セレクトボックスを参照
Dim selectElement = _browser.FindElement(By.Name("selectname"))
Dim selectObject = New SelectElement(selectElement)
'3つめのoptionの選択状態を取得
MsgBox(selectObject.Options(2).Selected)
'選択状態となっている全てのoptionを取得
For Each tmp In selectObject.AllSelectedOptions
MsgBox(tmp.GetAttribute("value"))
Next
End Sub
//下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
private void btnRef_Click(object sender, EventArgs e)
{
//テキストボックスを参照
MessageBox.Show(_browser.FindElement(By.Id("inputid2")).GetAttribute("value"));
//ラジオボタンを参照
MessageBox.Show(_browser.FindElements(By.Name("radioname"))[1].Selected.ToString());
//チェックボックスを参照
MessageBox.Show(_browser.FindElements(By.Name("checkname"))[0].Selected.ToString());
//セレクトボックスを参照
var selectElement = _browser.FindElement(By.Name("selectname"));
var selectObject = new SelectElement(selectElement);
//3つめのoptionの選択状態を取得
MessageBox.Show(selectObject.Options[2].Selected.ToString());
//選択状態となっている全てのoptionを取得
foreach (var tmp in selectObject.AllSelectedOptions)
{
MessageBox.Show(tmp.GetAttribute("value"));
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from tkinter import messagebox
from selenium.webdriver.support.select import Select
#Chromeブラウザを表示(環境変数のPATHにドライバーのパスを追加済とする)
driver = webdriver.Chrome()
#ページを表示
driver.get("https://web.biz-prog.net/test/testpage.html")
#テキストボックスを参照
element = driver.find_element(By.ID, "inputid2")
element.send_keys("テスト1")
messagebox.showinfo("テキストボックスの値:" + element.get_attribute("value"))
#ラジオボタンを参照
element = driver.find_elements(By.NAME, "radioname")[1]
element.click()
messagebox.showinfo("ラジオボタンの値:" + str(element.is_selected()))
#チェックボックスを参照
element = driver.find_elements(By.NAME, "checkname")[0]
element.click()
messagebox.showinfo("チェックボックスの値:" + str(element.is_selected()))
#セレクトボックスを参照
selectElement = driver.find_element(By.NAME, "selectname")
selectObject = Select(selectElement)
#3つめのoptionの選択状態を取得
selectObject.select_by_index(2)
messagebox.showinfo("オプションの選択状態:" + str(selectObject.options[2].is_selected()))
#選択状態となっている全てのoptionを取得
for tmp in selectObject.all_selected_options:
messagebox.showinfo("オプションの値:"+ tmp.get_attribute("value"))
Submit
formに対してsubmitを行う方法です。
実装方法
フォームの要素を特定して、Submitメソッドを実行します。
サンプル
'下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Dim formElement = _browser.FindElement(By.Name("testform1"))
formElement.FindElement(By.Id("inputid2")).SendKeys("テキスト2 id")
formElement.Submit()
End Sub
//下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
private void btnSubmit_Click(object sender, EventArgs e)
{
var formElement = _browser.FindElement(By.Name("testform1"));
formElement.FindElement(By.Id("inputid2")).SendKeys("テキスト2 id");
formElement.Submit();
}
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from tkinter import messagebox
from selenium.webdriver.support.select import Select
#Chromeブラウザを表示(環境変数のPATHにドライバーのパスを追加済とする)
driver = webdriver.Chrome()
#ページを表示
driver.get("https://web.biz-prog.net/test/testpage.html")
formElement = driver.find_element(By.NAME, "testform1")
formElement.find_element(By.ID, "inputid2").send_keys("テキスト2 id")
formElement.submit()
属性の参照・設定
要素の属性の値を参照・設定する方法です。
実装方法
属性の値を取得するにはGetAttributeメソッドを使用します。
引数に属性名を指定すれば、属性の値が返却されます。
属性の値を設定するメソッドはありませんので、代わりにJavaScriptのコードを実行する処理を使って、JavaScriptで設定を行います。
サンプル
Private Sub btnAttr_Click(sender As Object, e As EventArgs) Handles btnAttr.Click
'info属性の値を表示
MsgBox(_browser.FindElement(By.Id("styleid1")).GetAttribute("info"))
'文字のスタイル内容を表示
CType(_browser, IJavaScriptExecutor).ExecuteScript("document.getElementById('styleid1').setAttribute('info', 'newinfo');")
CType(_browser, IJavaScriptExecutor).ExecuteScript("alert(document.getElementById('styleid1').getAttribute('info'));")
End Sub
//下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
private void btnAttr_Click(object sender, EventArgs e)
{
//info属性の値を表示
MessageBox.Show(_browser.FindElement(By.Id("styleid1")).GetAttribute("info"));
//文字のスタイル内容を表示
((IJavaScriptExecutor)_browser).ExecuteScript("document.getElementById('styleid1').setAttribute('info', 'newinfo');");
((IJavaScriptExecutor)_browser).ExecuteScript("alert(document.getElementById('styleid1').getAttribute('info'));");
}
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from tkinter import messagebox
#Chromeブラウザを表示(環境変数のPATHにドライバーのパスを追加済とする)
driver = webdriver.Chrome()
#ページを表示
driver.get("https://web.biz-prog.net/test/testpage.html")
#info属性の値を表示
messagebox.showinfo(driver.find_element(By.ID, "styleid1").get_attribute("info"))
#文字のスタイル内容を表示
driver.execute_script("document.getElementById('styleid1').setAttribute('info', 'newinfo');")
driver.execute_script("alert(document.getElementById('styleid1').getAttribute('info'));")
スタイルの参照・設定
指定した要素のスタイルを設定・参照する方法です。
実装方法
スタイルの参照・設定はJavaScriptを使います。
サンプル
'下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
Private Sub btnStyle_Click(sender As Object, e As EventArgs) Handles btnStyle.Click
'ExecuteAsyncScriptで非同期に実行する場合、JavaScriptに'alert'が含まれていると、処理が止まる
'alertを閉じないまま、次のalertを表示すると、例外が発生する。
'背景色を変更
CType(_browser, IJavaScriptExecutor).ExecuteScript("document.body.style.backgroundColor = 'Red';")
'文字のスタイル内容を表示
CType(_browser, IJavaScriptExecutor).ExecuteScript("alert(document.getElementById('styleid1').style.cssText);")
MsgBox("ブラウザに表示されているalertを閉じてからOKを押す")
CType(_browser, IJavaScriptExecutor).ExecuteScript("alert(document.getElementById('styleid1').getAttribute('style'));")
MsgBox("ブラウザに表示されているalertを閉じてからOKを押す")
'文字のスタイルを変更
CType(_browser, IJavaScriptExecutor).ExecuteScript("document.getElementById('styleid1').style.cssText ='font-size: xx-large; font-style: italic; color: red;';")
CType(_browser, IJavaScriptExecutor).ExecuteScript("alert(document.getElementById('styleid1').style.cssText);")
MsgBox("ブラウザに表示されているalertを閉じてからOKを押す")
'文字のスタイルを変更2
CType(_browser, IJavaScriptExecutor).ExecuteScript("document.getElementById('styleid1').setAttribute('style', 'font-size: large; font-style: italic; color: green;');")
CType(_browser, IJavaScriptExecutor).ExecuteScript("alert(document.getElementById('styleid1').style.cssText);")
MsgBox("ブラウザに表示されているalertを閉じてからOKを押す")
'文字のスタイルを変更3
CType(_browser, IJavaScriptExecutor).ExecuteScript("document.getElementById('styleid1').style.color ='black';")
CType(_browser, IJavaScriptExecutor).ExecuteScript("alert(document.getElementById('styleid1').style.color);")
MsgBox("ブラウザに表示されているalertを閉じてからOKを押す")
End Sub
//下記コードの動作確認はテストページ(https://web.biz-prog.net/test/testpage.html)で
private void btnStyle_Click(object sender, EventArgs e)
{
//背景色を変更
((IJavaScriptExecutor)_browser).ExecuteScript("document.body.style.backgroundColor = 'Red';");
//文字のスタイル内容を表示
((IJavaScriptExecutor)_browser).ExecuteScript("alert(document.getElementById('styleid1').style.cssText);");
MessageBox.Show("ブラウザに表示されているalertを閉じてからOKを押す");
((IJavaScriptExecutor)_browser).ExecuteScript("alert(document.getElementById('styleid1').getAttribute('style'));");
MessageBox.Show("ブラウザに表示されているalertを閉じてからOKを押す");
//文字のスタイルを変更
((IJavaScriptExecutor)_browser).ExecuteScript("document.getElementById('styleid1').style.cssText ='font-size: xx-large; font-style: italic; color: red;';");
((IJavaScriptExecutor)_browser).ExecuteScript("alert(document.getElementById('styleid1').style.cssText);");
MessageBox.Show("ブラウザに表示されているalertを閉じてからOKを押す");
//文字のスタイルを変更2
((IJavaScriptExecutor)_browser).ExecuteScript("document.getElementById('styleid1').setAttribute('style', 'font-size: large; font-style: italic; color: green;');");
((IJavaScriptExecutor)_browser).ExecuteScript("alert(document.getElementById('styleid1').style.cssText);");
MessageBox.Show("ブラウザに表示されているalertを閉じてからOKを押す");
//文字のスタイルを変更3
((IJavaScriptExecutor)_browser).ExecuteScript("document.getElementById('styleid1').style.color ='black';");
((IJavaScriptExecutor)_browser).ExecuteScript("alert(document.getElementById('styleid1').style.color);");
MessageBox.Show("ブラウザに表示されているalertを閉じてからOKを押す");
}
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from tkinter import messagebox
#Chromeブラウザを表示(環境変数のPATHにドライバーのパスを追加済とする)
driver = webdriver.Chrome()
#ページを表示
driver.get("https://web.biz-prog.net/test/testpage.html")
#背景色を変更
driver.execute_script("document.body.style.backgroundColor = 'Red';")
#文字のスタイル内容を表示
driver.execute_script("alert(document.getElementById('styleid1').style.cssText);")
messagebox.showinfo("","ブラウザに表示されているalertを閉じてからOKを押す")
driver.execute_script("alert(document.getElementById('styleid1').getAttribute('style'));")
messagebox.showinfo("","ブラウザに表示されているalertを閉じてからOKを押す")
#文字のスタイルを変更
driver.execute_script("document.getElementById('styleid1').style.cssText ='font-size: xx-large; font-style: italic; color: red;';")
driver.execute_script("alert(document.getElementById('styleid1').style.cssText);")
messagebox.showinfo("","ブラウザに表示されているalertを閉じてからOKを押す")
#文字のスタイルを変更2
driver.execute_script("document.getElementById('styleid1').setAttribute('style', 'font-size: large; font-style: italic; color: green;');")
driver.execute_script("alert(document.getElementById('styleid1').style.cssText);")
messagebox.showinfo("","ブラウザに表示されているalertを閉じてからOKを押す")
#文字のスタイルを変更3
driver.execute_script("document.getElementById('styleid1').style.color ='black';")
driver.execute_script("alert(document.getElementById('styleid1').style.color);")
messagebox.showinfo("","ブラウザに表示されているalertを閉じてからOKを押す")
