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, 1361🔥, 0💬
Popular Posts:
How to find out my browser's identification information? To help you to see your browser identificat...
How to valid IP addresses? In order to help your programming or testing tasks, FYIcenter.com has des...
How to generate MAC addresses? To help you to obtain some MAC addresses for testing purpose, FYIcent...
How to generate test credit card numbers? Test credit card numbers are frequently needed in testing ...
How to access Response Status Code 400 as Success? My sampler failed, because the server returns the...