首页 > 解决方案 > 我如何从 python 导入一个 html 文件

问题描述

我想在 python 中导入一个 html 文件,以便在 python 代码中不写 html

我尝试读取 html 文件并将其内容放入变量中,但它不读取 css 内容

html = open("templates/email.html","r")
msg.add_alternative(html.read(),subtype="html")        
html.close()

例子:

import 'file.html' as html
msg.add_alternative(html,subtype="html") 

标签: pythonhtmlflasksmtp

解决方案


这将打开并读取将其放入列表变量的文件。

        fileName = "filepath of the html I want to read"
        htmlText = file.text.readlines(fileName)

如果您想在 htmlText 变量中(在 HTML 中)找到某个元素。我会建议一个 for 循环和一个子字符串查找方法,如下所示。

        for i in range(0, len(htmlText):
           line=htmlText[i]
           if (line.find('some element inside HTML') != -1):
                print("I found it")
                # some other action 

推荐阅读