簡體   English   中英

如何使用Selenium ExecuteScript函數獲取HashTable

[英]How to get HashTable with Selenium ExecuteScript function

使用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中獲取值后自行轉換這些值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM