将代码块捕获到python

时间:2018-07-21 21:07:38

标签: python html json

我想动态创建一个html代码块,但不确定如何将其分配给变量:

<head>
<style>
body {
    border-style: solid;
    border-width: 5px;
    border-color: green;
    border-radius: 5px;
    border-spacing: 30px;
    background-color: #FFFFC2;
    padding-bottom: 5px;
    font-size: 25px;
}

li {
    color: #F7270F;
    font-weight: bold;
}
</style>
</head>
<body>
<div style="margin-bottom: 5px; margin-top: 5px; margin-left: 10px; margin-right: 10px;">
<h1 align="center">Auctions for Week of 08-01-2018</h1>
<p>You are bidding on the following item:</p>
<ul><li>This is the item for sale</li></ul>
<p>Condition is pack fresh unless otherwise indicated. Please review the pictures carefully and if you have any questions about something specific, ask.</p>
<p><b>Shipping:</b> Shipping will be calculated based on buyer location. No premiums are charged. Cards are mailed in an 8x5 bubble mailer and shipped First Class mail unless the price exceeds $50, at which point they will be shipped Priority at no additional cost to the buyer. If you win multiple auctions, please wait for an invoice to be sent.</p>
</div>
</body>

我尝试执行:

html_desc="<code_block>"

但是它不喜欢它的工作方式...所以我有些困惑。我尝试将其放入变量的原因是因为我需要将其作为JSON语句的键值。

1 个答案:

答案 0 :(得分:1)

您可以将该代码块放在三引号"""内(例如,我将变量放在json.dumps内)

from pprint import pprint
import json

html_desc = """<head>
<style>
body {
    border-style: solid;
    border-width: 5px;
    border-color: green;
    border-radius: 5px;
    border-spacing: 30px;
    background-color: #FFFFC2;
    padding-bottom: 5px;
    font-size: 25px;
}

li {
    color: #F7270F;
    font-weight: bold;
}
</style>
</head>
<body>
<div style="margin-bottom: 5px; margin-top: 5px; margin-left: 10px; margin-right: 10px;">
<h1 align="center">Auctions for Week of 08-01-2018</h1>
<p>You are bidding on the following item:</p>
<ul><li>This is the item for sale</li></ul>
<p>Condition is pack fresh unless otherwise indicated. Please review the pictures carefully and if you have any questions about something specific, ask.</p>
<p><b>Shipping:</b> Shipping will be calculated based on buyer location. No premiums are charged. Cards are mailed in an 8x5 bubble mailer and shipped First Class mail unless the price exceeds $50, at which point they will be shipped Priority at no additional cost to the buyer. If you win multiple auctions, please wait for an invoice to be sent.</p>
</div>
</body>"""

pprint(json.dumps({html_desc: "Some Value"}))