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

我使用python编写了一个脚本,生成一个html文件。如何使用网络爬虫检索的数据动态更改其内容,python,html,web-crawler,Python,Html,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>""

我通过创建一个新的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()
newHtmlFile=open('todaysNBAScores.html','w')
newHtmlFile.write(“**如何动态更改此段落的内容?***”)
newHtmlFile.close()

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

我想我会这样做

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

with open('todaysNBAScores.html', 'w') as newHTMLFile:
    newHTMLFile.write(content)
    newHTMLFile.close()
dynamicContent=“Foo-Bar”
content=“%s”%(dynamicContent)
将open('todaysNBAScores.html','w')作为新的html文件:
newHTMLFile.write(内容)
newHTMLFile.close()
*.html文件将包含

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

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

您可以设计一个包含占位符变量的html模板,然后使用每次需要填充的值来呈现它

首先安装jinja2

pip install jinja2
您可以将html页面的结构作为模板提供,并使用特殊的
{{}
块显示数据应该填充的位置

然后,通过提供具有键/值对的字典来填充指定的块来呈现模板

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> Second page </Title><body> This is a different page </body>'
u'第二页这是另一页'
像jinja2这样的模板引擎可以轻松地在html上执行许多复杂的转换,因此,如果您所做的不仅仅是替换一个字符串,那么可能值得花时间使用这些东西

有关更多示例,请参见。

template='{}

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

with open('index.html') as html:
    html.write(template.format(newContent))
以html形式打开('index.html'): write(template.format(newContent))
字符串格式
'{}

'.format(value)
您必须使用lxml软件包。谢谢@MalikBrahimi两位,这样行吗?例:newContent=('05-08-2015 NBA总分109-107')|“{}”。格式(newContent)。@bartlenzo这是一个元组还是一个字符串?@MalikBrahimi string这正是上面评论中所写的。你不知道我有多高兴谢谢你。这真的很简单,但很有效。请用旁边的复选标记作为答案。
u'<Title> Second page </Title><body> This is a different page </body>'
template = '<html><body><p>{}</p></body></html>'

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