gpt4 book ai didi

c# - 使用 Selenium WebDriver 从 IWebElement 获取所有属性

转载 作者:太空狗 更新时间:2023-10-29 19:52:58 25 4
gpt4 key购买 nike

我想用 Selenium 从 DOM 中提取一些信息。我正在使用 C# WebDriver。

查看 IWebElement 接口(interface),您可以轻松提取给定的属性。但是,我想在事先不知道名称的情况下提取元素的所有属性。

一定有一些简单的方法可以做到这一点,因为有一种方法可以在您知道属性值的情况下获取属性值。

一个例子:

<button id="myButton" ng-click="blabla()" ng-show="showMyButton" 
some-other-attribute="foo.bar" />



IWebElement element = driver.FindElement(By.Id("myButton"));
Dictionary<string, string> attributes = new Dictionary<string, string>();
// ???????
// Profit.

希望我遗漏了一些明显的东西。

提前致谢!

最佳答案

JavaScript 中的 .attributes 属性将返回给定元素具有的所有属性及其值的数组。

所以您需要做的是首先获得一个能够运行 JavaScript 的驱动程序:

IJavascriptExecutor javascriptDriver = (IJavaScriptExecutor)driver;

现在,通过以下方式执行它:

Dictionary<string, object> 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<string, object>;

JavaScript 背后的想法是在元素本身中使用 JavaScript attributes 属性,然后提取我们需要的信息 - 属性的名称和值。 attributes 属性实际上提取了很多关于每个属性的信息,但我们只需要两个字段。所以我们得到这两个字段,将它们放入字典中,然后 WebDriver 将解析它返回给我们。 (可能会稍微清理一下)

它现在是一个 Dictionary,因此您可以随意循环。每对的将是属性的名称,每对的将是 属性。

仅使用散布在网络上的一些元素(此处为 Google 和一些小网页)对其进行了测试,它似乎运行良好。

关于c# - 使用 Selenium WebDriver 从 IWebElement 获取所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21681897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com