使用Selenium WebDriver,为了在C#中使用Tag获取所有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"
答案 0 :(得分: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>;
现在,有几点需要注意。第一个是来自ExecuteScript
的序列化程序不能很好地复用过于复杂的对象。这意味着如果一个属性有一个对象作为其值,这可能不会像你一样好用。作为一个例子,我不会尝试从JavaScript序列化jQuery对象。另一个警告是返回类型为Dictionary<string, object>
。如果您要创建Hashtable
或将值转换为字符串,则必须在从JavaScript获取值后自行转换这些值。