0

使用 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"
4

1 回答 1

3

为什么以下不起作用?

// 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>;

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

于 2013-09-03T16:11:46.060 回答