You can use ElementTree to parse through the HTML DOM, use the find method to search for img
tag. Then you can assign the src attribute value. The attributes are returned as a dict with the attrib
parameter and you just need to look for the 'src'
key:
import datetime
date = datetime.datetime.now().strftime('%Y%m%d')
filename = date + " snapshot.png"
import xml.etree.ElementTree as et
html = """
<html>
<head></head>
<body>
<img src="Directory/snapshot.png"/>
</body>
</html>
"""
tree = et.fromstring(html)
image_attributes = tree.find('body/img').attrib
for k in image_attributes.keys():
if 'src' in k:
image_attributes[k] = filename
html_new = et.tostring(tree)
print(html_new)
Output:
b'<html>n <head />n <body>n <img src="20200220 snapshot.png" />n </body>n</html>'
To pretty print this output, you can use the method provided in official docs here and just do:
et.dump(tree)
Output:
<html>
<head />
<body>
<img src="20200220 snapshot.png" />
</body>
</html>