我们有下面的 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/