如何在 python 中向 HTML 添加类和样式表?
Posted
技术标签:
【中文标题】如何在 python 中向 HTML 添加类和样式表?【英文标题】:How to add classes and stylesheets to HTML in python? 【发布时间】:2021-06-29 00:45:27 【问题描述】:我正在从 API 中抓取数据并使用 html_file.write 方法将它们输入到 html 文件中。我想将文本居中并添加边框和字体等。但是当我将例如 .content 类添加到
html_content=f"<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"/>"+"""
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Questrial&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<style>
.content
width: 50%;
margin: auto;
background: white;
padding: 10px;
img
max-width: 100%;
body background-color: LightGray;
h1 color: red;
h2 color: red;
</style>
"""+f"</head><body><div class="container"><h1><h1><font size='6'><strong>Q</strong></font></h1><p>content2modified</p><hr><h1><font size='6'><strong>A</strong></font></h1><p>contentmodified</p> </body></div> </html>"
with open("index.html","w",encoding='utf-8') as html_file:
html_file.write(html_content)
print("Success")
await message.author.send(file=discord.File('index.html'))
【问题讨论】:
【参考方案1】:尝试在 f 字符串中复制括号。 '' -> '' 和 '' -> ''
【讨论】:
不,容器上的语法仍然无效【参考方案2】:想通了:
html_content=f"<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"/>"+"""
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Questrial&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<style>
h1
font-family: 'Questrial', sans-serif;
p
font-family: 'Questrial', sans-serif;
.content
width: 100%;
margin: auto;
background: white;
padding: 10px;
img
max-width: 100%;
body background-color: LightGray;
h1 color: red;
</style>
</head><body><div class="container"><div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<center><strong>Powered by Kurdi. Join our Discord server: https://discord.gg/4UNjM6Cy </strong>
</div><div class="content"">"""+f"<h1><h1><font size='6'><strong>Q</strong></font></h1><p>r5</p><hr><h1><font size='6'><strong>A</strong></font></h1><p>anshtml</p> </body></div> </html>"
【讨论】:
以上是关于如何在 python 中向 HTML 添加类和样式表?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 python 中向 Mnist 数据集添加 50% 的随机正常噪声
如何在 Python 3.7 中向 multiprocessing.connection.Client(..) 添加超时?