【问题标题】:How to get HashTable with Selenium ExecuteScript function如何使用 Selenium ExecuteScript 函数获取 HashTable
【发布时间】:2013-09-06 21:31:55
【问题描述】:

使用 Selenium WebDriver,要一次获取 C# 中标记的所有 html 属性,我这样做

ReadOnlyCollection<object> HtmlAttributes = (ReadOnlyCollection<object>)((IJavaScriptExecutor)Driver).ExecuteScript("var s = []; var attrs = arguments[0].attributes; for (var l = 0; l < attrs.length; ++l) { var a = attrs[l]; s.push(a.name + ':' + a.value); } ; return s;", ele);

但是通过这段 JavaScript 代码,我得到了一个包含值的数组:

HtmlAttributes[index] = "HtmlAttribute:Value".

是否有可能获得哈希表?例如:

HtmlAttributes[HtmlAttribute] = "Value"

【问题讨论】:

    标签: c# javascript selenium selenium-webdriver


    【解决方案1】:

    为什么以下方法不起作用?

    // Putting this all on one line would work just fine; I'm
    // breaking it out here for readability.
    string script = 
        @"var s = {};
          var attrs = arguments[0].attributes;
          for (var index = 0; index < attrs.length; ++index) {
            var a = attrs[index];
            s[a.name] = a.value;
          }
          return s;";
    
    // Direct casting would work in a single line as well.
    // Again, using the "as" operator and multiple lines for
    // readability.
    // ASSUMPTIONS: "driver" is a valid IWebDriver object, and
    // "element" is a valid IWebElement object found using FindElement.
    IJavaScriptExecutor executor = driver as IJavaScriptExecutor;
    Dictionary<string, object> attributes = executor.ExecuteScript(script, element) as Dictionary<string, object>;
    

    现在,有几点需要注意。首先是来自ExecuteScript 的序列化程序不能很好地递归过于复杂的对象。这意味着如果一个属性有一个对象作为它的值,这可能不会像你想要的那样工作。例如,我不会尝试从 JavaScript 序列化 jQuery 对象。另一个警告是返回类型将是Dictionary&lt;string, object&gt;。如果您想创建Hashtable,或将值转换为字符串,则必须在从 JavaScript 获取值后自行转换这些值。

    【讨论】:

      猜你喜欢
      • 2016-07-13
      • 2017-12-12
      • 2012-04-22
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多