2011-11-26 43 views
0

我可以獲取元素中存在的所有屬性嗎?如何使用Watin獲取標籤中的屬性集合?

我需要這個遍歷元素中的所有屬性並獲取值!

我已搜查的元素類,但我不能看到具體的返回屬性字符串名稱的集合,所以我可以遍歷和GetAttributeValue任何屬性或方法....

讚賞任何幫助。

謝謝。

回答

0

我寫了一個方法來做到這一點,因爲(據我所知),WatiN沒有內置任何東西。自從這個代碼我沒有任何問題,但我仍然認爲這是一個可怕的黑客!也許這裏更聰明的海報可以幫助改善它! HTH!

菲爾

private void button1_Click(object sender, EventArgs e) 
{ 
    using (IE browser = new IE("www.google.co.uk")) 
    { 
     Div div = browser.Div("hplogo"); 
     Dictionary<string, string> attrs = GetAllAttributeValues(div); 
    } 
} 

private Dictionary<string, string> GetAllAttributeValues(Element element) 
{ 
    if (element == null) 
     throw new ArgumentNullException("Supplied element is null"); 
    if (!element.Exists) 
     throw new ArgumentException("Supplied element does not exist"); 

    string html = element.OuterHtml; // element html (incl children) 
    int idx = html.IndexOf(">"); 
    Debug.Assert(idx != -1); 
    html = html.Substring(0, idx + 1).Trim(); // element html without children 

    Dictionary<string, string> result = new Dictionary<string, string>(); 
    while ((idx = html.IndexOf('=')) != -1) 
    { 
     int spaceIdx = idx - 1; 
     while (spaceIdx >= 0 && html[spaceIdx] != ' ') 
      spaceIdx--; 
     Debug.Assert(spaceIdx != -1); 

     string attrName = html.Substring(spaceIdx + 1, idx - spaceIdx - 1); 
     string attrValue = element.GetAttributeValue(attrName); 
     result.Add(attrName, attrValue); 

     html = html.Remove(0, idx + 1); 
    } 
    return result; 
} 
+0

剛剛發現此代碼的潛在問題。如果其中一個屬性值包含'=',它會嘗試並將其解析爲另一個屬性:S也許您可以將字符串解析爲xml以獲取它們的鍵值對。 –

0

您可以使用HtmlAgilityPack的一樣。它提供HtmlNode.Attributes作爲HtmlAttributeCollection,可以循環獲取屬性名稱和值。

+0

您能否詳細說明您的答案,並添加關於您提供的解決方案的更多描述? – abarisone

相關問題