使用Selenium WebDriver从IWebElement获取所有属性
我想用Selenium从DOM中提取一些信息。 我正在使用C#WebDriver。
查看IWebElement接口,您可以轻松提取给定属性。 但是,我想提取一个元素的所有属性,而不需要事先知道它们的名字。
必须有一些简单的方法来执行此操作,因为如果您知道其名称,则有一种获取属性值的方法。
一个例子:
IWebElement element = driver.FindElement(By.Id("myButton")); Dictionary attributes = new Dictionary(); // ??????? // Profit.
希望我错过了一些明显的东西。
提前致谢!
JavaScript中的.attributes
属性将返回给定元素具有的所有属性的数组及其值。
所以你需要做的是首先获得一个能够运行JavaScript的driver
:
IJavascriptExecutor javascriptDriver = (IJavaScriptExecutor)driver;
现在,执行它:
Dictionary attributes = javascriptDriver.ExecuteScript("var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;", element) as Dictionary;
JavaScript背后的想法是使用元素本身中的JavaScript attributes
属性,然后提取我们需要的信息 – 属性的名称和值。 实际上, attributes
属性提取了有关每个属性的大量信息,但我们只需要两个字段。 所以我们得到这两个字段,将它们放入字典中,然后WebDriver将它解析回给我们。 (它可能会被清理一下)
它现在是一个Dictionary
,因此你可以随心所欲地循环。 每对的key
将是属性的名称 ,每对的值将是属性的值 。
只有在网络上点缀了一些元素(这里是谷歌和一些小网页)才对它进行测试,它似乎运行良好。
你可以试试这个:
IWebElement element = driver.FindElement(By.Id("myButton")); string elementHtml = element.GetAttribute("outerHTML");
这将为您提供元素的html。 从这里开始,你可以解析它,正如Arran建议的那样
你可以做一个FindElement(By.tag(“body”))来返回一个WebElements列表,然后按照你的建议解析结果。
你可以试试这个:
Actions newTab = new Actions(web driver); newTab.ContextClick(element).SendKeys(Keys.ArrowDown).SendKeys(Keys.ArrowDown).SendKeys(Keys.Return).Build().Perform();
List el = new List (); el.AddRange(driver.FindElements(By.CssSelector("*"))); List ag= new List (); for (int b = 0; b < el.Count; b++) { ag.Add(el[b].GetAttribute("outerHTML")); }