Collections:
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): print(space+"<"+tag.tag_name+attributes+"/>") else: print(space+"<"+tag.tag_name+attributes+">") for child in list: printTagWithAttributes(child,space+" ") print(space+"</"+tag.tag_name+">") driver = Chrome() driver.get("http://sqa.fyicenter.com") html = driver.find_element_by_tag_name("html") printTagWithAttributes(html,"") driver.quit()
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 <html> <head> <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"/> <title/> <script src="https://....."/> <script id="google_shimpl" src="https://..."/> <script/> ... </head> <body> <div class="c1" id="left"> <div class="r2" id="links"> <p class="head"/> <p class="link"> <a href="/1000036_Apache_JMeter_Tutorials.html"/> </p> <p class="link"> <a href="/1000128_Test_Management_Tutorials.html"/> </p> ... </div> </div> </body> </html>
The output looks good.
⇒ Load HTML Files with WebDriver in Python
⇐ Dump Elements with find_elements_by_xpath() in Python
2019-10-18, 1276🔥, 0💬
Popular Posts:
Where to find tutorials on Test Management? I want to know how to manage software testing documents ...
How to force JMeter to automatically flush test result to file immediately after each sampler is exe...
How to validate domain name format? In order to help your programming or testing tasks, FYIcenter.co...
Where to find tutorials on UFT (Unified Functional Testing) tool? I want to know how to use UFT. Her...
How to see my IP address Host Name? To help you to see your IP Address Host Name, FYIcenter.com has ...