Getting ALL attributes from an IWebElement with Selenium WebDriver

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 can try this:

IWebElement element = driver.FindElement(By.Id("myButton"));

string elementHtml = element.GetAttribute("outerHTML");

This will give you the html of the element. From here, you can parse it, as Arran suggested