python - 如何在python中读取html标签内的多个变量值

标签 python html

我们有下面的 html 代码,它用一个变量在 python 中调用

html123='''
<html>
<head>
<style>
div {
  background-color: lightgrey;
  width: 300px;
  border: 15px solid green;
  padding: 50px;
  margin: 20px;
}
</style>
</head>
<body>

<h2>Demonstrating the Box Model</h2>

<div>This text is $Var1</div>

</body>
</html>
</html>   '''

对于一个变量,我尝试了以下方法

from string import Template
s = Template(html123).safe_substitute(Var1=LockingVar)  

如果我有多个变量

html123='''
<html>
<head>
<style>
div {
  background-color: lightgrey;
  width: 300px;
  border: 15px solid green;
  padding: 50px;
  margin: 20px;
}
</style>
</head>
<body>

<h2>Demonstrating the Box Model</h2>

<div>This text is $Var1</div>
<div>This text is $Var2</div>
<div>This text is $Var3</div>

</body>
</html>
</html>   '''

但是如果我们在html标签中有多个变量Var1,var2,var3,我们如何映射这些变量值。

请提出任何建议..

最佳答案

向 safe_substitute 提供一个字典

>>> params = {
...  'Var1':'aa',
...  'Var2':'bb',
...  'Var3':'cc'
... }

>>> Template("$Var1 $Var2 $Var3").safe_substitute(params)  
"aa bb cc"

关于python - 如何在python中读取html标签内的多个变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64946763/

相关文章:

python - 将 Pandas 列转换为数据框

Python 自定义模块名称未定义

javascript - jquery 中的 on() 函数不起作用

jquery - Bootstrap navbar-fixed-top 隐藏页面内容

html - 试图在我的导航栏中居中图像

html - 防止表格尺寸失真

python - 无法使用 cx-Oracle 插入 Unicode

python - Discogs API => 如何检索流派?

jquery - 如何在 css 中的梯形内插入文本?

python - flask 将变量从一个函数传递到另一个函数