【问题标题】:Add Javascript into Python created html将 Javascript 添加到 Python 创建的 html 中
【发布时间】:2022-06-30 01:48:46
【问题描述】:

您好,我有一个创建单个 html 文件的 python 脚本,但我不知道如何将 javascript 添加到其中

import pathlib
import os
 
html = ""
 
for file in pathlib.Path(".").iterdir():
    if file.is_file():
        if str(file).endswith(".png"):
            html += f"<center><img src='{file}'/ height=100%></center><br>"
            
 
with open("index2.html", "w") as outputfile:
    outputfile.write(html)
 
os.startfile("index2.html")

到目前为止我已经尝试过

import pathlib
import os
 
html = ""
 
for file in pathlib.Path(".").iterdir():
    if file.is_file():
        if str(file).endswith(".png"):
            html += f"<center><img src='{file}'/ height=50%></center><br><script>var imagesrc = document.getElementById("image.png").src;"

 
with open("index2.html", "w") as outputfile:
    outputfile.write(html)
 
os.startfile("index2.html")

但这似乎根本不起作用

任何帮助将不胜感激,谢谢

【问题讨论】:

    标签: javascript python html


    【解决方案1】:

    假设您的目录中有一个script.js 文件:

    # File.py
    html += "<script type=\"text/javascript\" src=\"script.js\"></script>"
    

    如果你想直接在.html文件中,你可以这样做:

    html += f"<script type=\"text/javascript\">{javascript_content}</script>"
    

     

    【讨论】:

    • 如果可能的话,我试图将它放入一个 html 文件中
    • 在这种情况下,您只需将代码复制粘贴到脚本标签中,我正在编辑我的答案
    【解决方案2】:

    这可能不起作用,因为您的“(引号)在“image.png”处打断了您的字符串,您可以使用单个撇号,或者使用反斜杠对其进行转义。

    html += f"<center><img src='{file}'/ height=50%></center><br><script>var imagesrc = document.getElementById(\"image.png\").src;"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 2013-03-09
      • 2022-01-02
      • 2011-06-10
      • 2022-01-23
      相关资源
      最近更新 更多