32
36

More than 5 years have passed since last update.

Selenium実行中にJavaScriptのコードを実行する

Last updated at Posted at 2014-06-23

Selenium実行中にJavaScriptのコードを実行する

JavaScriptで画面の値を取得/設定するコードをメモ。

WebDriverEx.cs
// JavaScriptを実行(戻り値なし)
public static void ExecuteJavaScript(this IWebDriver driver, string script)
{
    if (driver is IJavaScriptExecutor)
        ((IJavaScriptExecutor)driver).ExecuteScript(script);
    else
        throw new WebDriverException();
}

// JavaScriptを実行(戻り値あり)
public static T ExecuteJavaScript<T>(this IWebDriver driver, string script)
{
    if (driver is IJavaScriptExecutor)
        return (T)((IJavaScriptExecutor)driver).ExecuteScript(script);
    else
        throw new WebDriverException();
}

使い方
// <input name="hoge">のvalueに「1234567890」を設定
driver.ExecuteJavaScript("document.getElementsByName('hoge')[0].value = '1234567890';");

// <input name="hoge" maxlength="8">のmaxlengthを削除
driver.ExecuteJavaScript("document.getElementsByName('hoge')[0].removeAttribute('maxlength');");

// ページのタイトルをstring型で取得
string str = driver.ExecuteJavaScript<string>("return document.title;");

// ブラウザの現在時刻をDateTime型で取得
DateTime date = driver.ExecuteJavaScript<DateTime>("return new Date();");

IWebElementをJavaScriptで操作する。

By.IdやBy.Nameで取得したIWebElementをJavaScriptで操作するには、
スクリプトの後に引数を追加します。

WebDriverEx.cs
// JavaScriptを実行(戻り値なし)
public static void ExecuteJavaScript(this IWebDriver driver, string script, params object[] args)
{
    if (driver is IJavaScriptExecutor)
        ((IJavaScriptExecutor)driver).ExecuteScript(script, args);
    else
        throw new WebDriverException();
}

使い方
// argumentsに引数の配列が渡されます。
IWebElement e = driver.FindElement(By.Name("hoge"));
driver.ExecuteJavaScript("arguments[0].value = 'piyo';", e);
32
36
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
32
36