【问题标题】:How to import html file into python variable?如何将html文件导入python变量?
【发布时间】:2019-01-18 13:08:34
【问题描述】:

我正在尝试使用 python、MIMEMultipart 和 smtp 发送 html 电子邮件。 html很长,所以我把所有的html放在一个html文件中。现在我想将 html 文件导入我的 python 文件(在同一个文件夹中)并将所有 html 设置为一个名为 html_string 的 python 变量中的字符串。

html:

<html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>Welcome to infinity2o</title>
      <style type="text/css">
        body {
          padding-top: 0 !important;
          padding-bottom: 0 !important;
          padding-top: 0 !important;
          padding-bottom: 0 !important;
          margin: 0 !important;
          width: 100% !important;
          -webkit-text-size-adjust: 100% !important;
          -ms-text-size-adjust: 100% !important;
          -webkit-font-smoothing: antialiased !important;
        }
    .
    .
    .
    </head>
</html>

如何将所有 html 导入我的 python 文件并将其设置为等于一个变量:

蟒蛇:

html_string = """
   <html>
        <head>
          <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
          <title>Welcome to infinity2o</title>
          <style type="text/css">
            body {
              padding-top: 0 !important;
              padding-bottom: 0 !important;
              padding-top: 0 !important;
              padding-bottom: 0 !important;
              margin: 0 !important;
              width: 100% !important;
              -webkit-text-size-adjust: 100% !important;
              -ms-text-size-adjust: 100% !important;
              -webkit-font-smoothing: antialiased !important;
            }
        .
        .
        .
        </head>
    </html> """

【问题讨论】:

标签: python html smtp mime


【解决方案1】:

您可以打开文件,读取其所有内容,并将其设置为一个变量:

with open('html_file.html', 'r') as f:
    html_string = f.read()

【讨论】:

    【解决方案2】:

    只需像在任何 I/O 中一样打开文件。

    with open('test.html', 'r') as f: 
            html_string = f.read()
    

    【讨论】:

      【解决方案3】:

      你可以简单地使用以下

      fname = "FILE.html"
      html_file = open(fname, 'r', encoding='utf-8')
      source_code = html_file.read() 
      print(source_code)
      

      它会打印整个 .html 文件,如下面的 Spyder 截图所示

      【讨论】:

        猜你喜欢
        • 2021-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多