Collections:
Load HTML Files with WebDriver in Python
How to load an HTML document file from the local hard disk with WebDriver in Python?
✍: FYIcenter.com
If you want to load an HTML document file from the local hard disk with WebDriver,
you can use the "file" URI format to identify the local file
as shown in the example Python program below:
# LoadLocalHtmlFile.py
# Copyright (c) FYIcenter.com
from selenium.webdriver import Chrome
import pathlib
import sys
import os
file = sys.argv[1]
path = os.path.abspath(file)
url = pathlib.Path(path).as_uri()
print("Loading "+url)
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(url)
html = driver.find_element_by_tag_name("html")
printTagWithAttributes(html,"")
driver.quit()
To test the above program, you can use the following HTML file, Hello.html:
<html>
<head>
<title>Hello</title>
</head>
<body bgcolor="#ffeeee">
<p>Hello world!</p>
</body>
</html>
Run the program with Hello.html:
C:\fyicenter> python LoadLocalHtmlFile.py Hello.html
Loading file:///C:/fyicenter/Hello.html
<html{}>
<head{}>
<title{}>
</title>
</head>
<body{bgcolor=#ffeeee}>
<p{}>
</p>
</body>
</html>
The output shows that we loaded the local HTML file correctly.
⇒ Hidden Input Field with WebDriver in Python
⇐ Dump Element Attributes with execute_script() in Python
2019-10-18, 9052🔥, 0💬
Popular Posts:
How to validate domain name format? In order to help your programming or testing tasks, FYIcenter.co...
In what order thread groups are executed in JMeter? Thread groups, including regular "Thread Groups"...
How to valid IP addresses? In order to help your programming or testing tasks, FYIcenter.com has des...
How to set Content-Type to application/json? The server requires the Content-Type to be application/...
How to perform UUDecode (Unix-to-Unix Decode)? UUEncode is Unix-to-Unix encoding used on Unix system...