简体   繁体   English

混合 HTML 和 Python 代码 - 如何在 HTML 代码中引用不断变化的文件名

[英]Mixing HTML and Python code - how to refer to a changing filename within the HTML code

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.例如,我想将今天的文件引用为“20200219 snapshot.png”,明天将其更改为“20200220 snapshot.png”。 The problem is, I can't input the variable name filename after the img src and have to put in the hardcoded exact String.问题是,我无法在 img src 之后输入变量名文件名,而必须输入硬编码的确切字符串。

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

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

You can use ElementTree to parse through the HTML DOM, use the find method to search for img tag.您可以使用ElementTree解析 HTML DOM,使用find方法搜索img标签。 Then you can assign the src attribute value.然后您可以分配 src 属性值。 The attributes are returned as a dict with the attrib parameter and you just need to look for the 'src' key:属性作为带有attrib参数的 dict 返回,您只需要查找'src'键:

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>

Just make it a string preceded by f and add your variable between {} to the string只需将其设为以f开头的字符串,并将{}之间的变量添加到字符串中

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM