我使用 python 创建了一个生成 html 文件的脚本。如何使用网络爬虫检索的数据动态更改其内容

I made a script using python that generates a html file. How can I dynamically change its content using data being retrieved by a web crawler

我通过创建一个新的 html 文件开始我的代码 我使用 pycharm 作为我的 IDE 为简单起见,我将跳到由以下代码创建的新 html 文档的正文部分。

newHtmlFile = open('todaysNBAScores.html', 'w')
newHtmlFile.write("""<body><p>**How can I dynamically change the content of this paragraph ?**<p></body>""")

newHtmlFile.close()

虽然我还没有创建爬虫,但我只需要一个字符串变量的简单示例来替换 <p></p> 标签中的当前信息。

我想我会这样做。

dynamicContent = "Foo Bar"
content = "<body><p>%s<p></body>" % (dynamicContent) 

with open('todaysNBAScores.html', 'w') as newHTMLFile:
    newHTMLFile.write(content)
    newHTMLFile.close()

*.html 文件将包含

<body><p>Foo Bar<p></body>

如果您想使用 python 动态生成 HTML 文件,有很多选择。一种好方法是使用 Jinja2 模板引擎。

你设计了一个 html 模板,里面有占位符变量,然后你 render 它有你的值每次都要填写。

首先安装jinja2

pip install jinja2

您提供 html 页面的结构作为模板,其中包含特殊的 {{ }} 块,显示应在何处填写数据。

然后通过提供包含 Key/Value 对的字典来填充指定的块来呈现模板。

import Template from jinja2

t = Template("<Title> {{ title }} </Title><body> {{ content }} </body>")
dict = {"title": "First page", "content": "This is the first page"}
t.render(dict)

结果是插入值的新字符串

u'<Title> First page </Title><body> This is the first page </body>'

您可以使用不同的值再次渲染它以获得不同的结果

dict["title"] = "Second page"
dict["content"] = "This is a different page"
t.render(dict)

结果:

u'<Title> Second page </Title><body> This is a different page </body>'

像 jinja2 这样的模板引擎可以很容易地在 html 上做很多复杂的转换,所以如果你做的不仅仅是替换一个字符串,那么花时间使用这些东西可能是值得的.

有关更多示例,请参阅 documentation

template = '<html><body><p>{}</p></body></html>'

with open('index.html') as html:
    html.write(template.format(newContent))