gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:19:33 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com