Getting ALL attributes from an IWebElement with Selenium WebDriver

0
0

I want to extract some information from the DOM with Selenium. I’m using the C# WebDriver.

Looking at the IWebElement interface you can easily extract a given attribute. However, I would like to extract all the attributes of an element without knowing their names in before hand.

There must be some simple way of doing this since there is a method for getting an attribute value if you know its name.

An example:

<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.

Hopefully I’m missing something obvious.

Thanks in advance!

  • You must to post comments
0
0

The .attributes property in JavaScript will return an array of all the attributes a given element has and it’s value.

So what you’ll need to do is first get a driver that has the capability to run JavaScript:

IJavascriptExecutor javascriptDriver = (IJavaScriptExecutor)driver;

Now, execute it by:

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>;

The idea behind the JavaScript is to use the JavaScript attributes property within the element itself and then pull out the information we need – the name and value of the attribute. The attributes property, in reality, pulls a lot of information about each individual property but we want only two fields. So we get those two fields, put them into a dictionary and WebDriver will then parse it back to us. (It could probably be cleaned up a bit)

It’s now a Dictionary and thus you can loop through however you like. The key of each pair will be the name of the attribute, and the value of each pair will be the value of the attribute.

Only tested this with a few elements dotted around the web (here, Google, and a few small web pages) and it seems to work well.

  • You must to post comments
Showing 1 result
Your Answer
Post as a guest by filling out the fields below or if you already have an account.
Name*
E-mail*
Website