Dump Element Attributes with JavascriptExecutor in Java


How to dump all attributes of an HTML element with WebDriver in Java?

✍: FYIcenter.com


The WebElement API provided in WebDriver offers only one method to retrieve the attribute value of a given attribute name using the getAttribute(name) method.

So there is no way to dump all attributes of an HTML element with the WebElement API, since you don't know what attributes are specified in the HTML element.

One way to solve the problem is to run a JavaScript code use the JavascriptExecutor interface, as shown in the following example program.

// DumpElementsWithAttributes.java
// Copyright (c) FYIcenter.com 
import org.openqa.selenium.*;
public class DumpElementsWithAttributes {
   public static void main(String[] args) {
      WebDriver driver = WebDriverLoader.load(args[0]);
      JavascriptExecutor executor = (JavascriptExecutor) driver;

    WebElement html = driver.findElement(By.tagName("html"));

   public static void printTagWithAttributes(WebElement tag, String space, 
      JavascriptExecutor executor) {
      String script = "var items = {};"
         + " for (index = 0; index < arguments[0].attributes.length; ++index)"
         + " { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value };"
         + " return items;";
    Object attributes = executor.executeScript(script,tag);
    java.util.List<WebElement> list = tag.findElements(By.xpath("./*"));
    if (list==null) {
    } else {
         for (WebElement child: list) {
      printTagWithAttributes(child,space+"  ",executor);

Compile and run the program, you will see that all elements of the Web page are dumped with their attributes in the output:

C:\fyicenter> javac -classpath \
   .;\fyicenter\selenium\java\client-combined-3.141.59.jar \

C:\fyicenter> java -classpath \
   \fyicenter\selenium\java\libs\commons-exec-1.3.jar \
   DumpElementsWithAttributes Chrome

    <meta{content=text/html; charset=utf-8, http-equiv=Content-Type}>
    <meta{content=IE=edge, http-equiv=X-UA-Compatible}>
    <link{href=_style.css, rel=stylesheet, type=text/css}>
    <div{class=c1, id=left}>
      <div{class=r2, id=links}>

The output looks good.


Load HTML Files with WebDriver in Java

Dump Elements with By.xpath() in Java

Using Selenium WebDriver Client Java API

⇑⇑ Selenium Tutorials

2019-12-19, 1404🔥, 0💬