• [转载]Selenium実行中にJavaScriptのコードを実行する


    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);
    
  • 相关阅读:
    case when then用法
    查询后n条记录
    自定义函数
    字符函数
    数字运算符和函数
    时间日期函数
    mysql加密函数
    比较运算符和函数
    文件夹中的文件以目录的形式呈现
    错误提示:通过 Web 服务器的身份验证的用户无权打开文件系统上的文件
  • 原文地址:https://www.cnblogs.com/c-x-a/p/7994162.html
Copyright © 2020-2023  润新知