c# - 如何使用 Selenium ExecuteScript 函数获取 HashTable

标签 c# javascript selenium selenium-webdriver

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

最佳答案

为什么下面的方法不起作用?

// 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<string, object> 。如果你想创建一个Hashtable ,或将值转换为字符串,您必须在从 JavaScript 获取值后自行转换这些值。

关于c# - 如何使用 Selenium ExecuteScript 函数获取 HashTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18595825/

相关文章:

c# - 错误: Assembly uses System. Web.Mvc,引用程序集的版本较高

C# 将 Dapper POCO 和 Dapper.Fluent EntityMap 作为参数传递

Selenium 点击 Highcharts 系列

c# - 在 C# 中更改 XML 元素值

c# - CSS 中的 JavaScript 在回发时丢失 (ASP.NET)

javascript - 如何使用 javascript 替换 API URI 路径中的值以生成完整的 URL?

javascript - 重用 jquery-ajax 调用中传递的 'data'

javascript - 当您使用 jQuery .removeClass() 时,它会在没有该类的元素上运行时返回错误吗?

python - Selenium xpath all (//*) 不采用每个 css 元素

键盘无法访问 Python Selenium 元素