Dump Element Attributes with execute_script() in Python


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

✍: FYIcenter.com


The WebElement API provided in WebDriver offers only one method to retrieve the attribute value of a given attribute name using the get_attribute(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 execute_script() method, as shown in the following example program.

# DumpElementsWithAttributes.py
# Copyright (c) FYIcenter.com 
from selenium.webdriver import Chrome

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;"
def printTagWithAttributes(tag, space):
   global script
   global driver

#  build the attribute list
   attributes = ""
   dict = driver.execute_script(script,tag)
   for k, v in dict.items():
      attributes += " "+k+"=\""+v+"\""

   list = tag.find_elements_by_xpath("./*")
   if (len(list)==0):
      for child in list:
         printTagWithAttributes(child,space+"  ")

driver = Chrome()
html = driver.find_element_by_tag_name("html")

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

C:\fyicenter> python DumpElementsWithAttributes.py

    <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"/>
    <script src="https://....."/>
    <script id="google_shimpl" src="https://..."/>
    <div class="c1" id="left">
      <div class="r2" id="links">
        <p class="head"/>
        <p class="link">
          <a href="/1000036_Apache_JMeter_Tutorials.html"/>
        <p class="link">
          <a href="/1000128_Test_Management_Tutorials.html"/>

The output looks good.


Load HTML Files with WebDriver in Python

Dump Elements with find_elements_by_xpath() in Python

Using Selenium WebDriver Client Python API

⇑⇑ Selenium Tutorials

2019-10-18, 1204🔥, 0💬