Solution 1 :

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>

Solution 2 :

Just make it a string preceded by f and add your variable between {} to the string

import datetime
date = datetime.datetime.now().strftime('%Y%m%d')
filename = date + " snapshot.png" 

html = f"""
<html>
  <head></head>
    <body>
      <img src="Directory/{filename}"/>
    </body>
</html>
"""

print(html)

Or use simple string concatenation instead

import datetime
date = datetime.datetime.now().strftime('%Y%m%d')
filename = date + " snapshot.png" 

html = f"""
<html>
  <head></head>
    <body>
      <img src="Directory/"""
html += filename
html += """/>
    </body>
</html>
"""

print(html)

Problem :

I’m trying to automate a process where I take a snapshot everyday but change the filename to that date. For example, I’d like to reference today’s file as “20200219 snapshot.png” and change it to “20200220 snapshot.png” tomorrow. The problem is, I can’t input the variable name filename after the img src and have to put in the hardcoded exact String.

date = date.strftime('%Y%m%d')
filename = date + " snapshot.png" 

html = """
<html>
  <head></head>
    <body>
      <img src="Directory/snapshot.png"/>
    </body>
</html>
"""

Comments

Comment posted by Green Cloak Guy

Use an f-string?

By