我可以获取元素中存在的所有属性吗?如何使用Watin获取标签中的属性集合?
我需要这个遍历元素中的所有属性并获取值!
我已搜查的元素类,但我不能看到具体的返回属性字符串名称的集合,所以我可以遍历和GetAttributeValue任何属性或方法....
赞赏任何帮助。
谢谢。
我可以获取元素中存在的所有属性吗?如何使用Watin获取标签中的属性集合?
我需要这个遍历元素中的所有属性并获取值!
我已搜查的元素类,但我不能看到具体的返回属性字符串名称的集合,所以我可以遍历和GetAttributeValue任何属性或方法....
赞赏任何帮助。
谢谢。
我写了一个方法来做到这一点,因为(据我所知),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;
}
您可以使用HtmlAgilityPack的一样。它提供HtmlNode.Attributes
作为HtmlAttributeCollection
,可以循环获取属性名称和值。
您能否详细说明您的答案,并添加关于您提供的解决方案的更多描述? – abarisone
刚刚发现此代码的潜在问题。如果其中一个属性值包含'=',它会尝试并将其解析为另一个属性:S也许您可以将字符串解析为xml以获取它们的键值对。 –