如何使用python将字典值插入html模板文件?

问题描述 投票:1回答:1

我有一个html模板文件,如下所示,我想用python脚本中的字典值替换标题和正文。

<!DOCTYPE html>

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title>#Want to insert dictionary values here in python></title>
  <LINK href="styles.css" rel="stylesheet" type="text/css">
</head>

<body>

<img src="forkit.gif" id="octocat" alt="" />

<!-- Feel free to change this text here -->
<p>
   #Want to insert dictionary values here in python>
</p>
<p>
  #Want to insert dictionary values here in python>
</p>

</body>
</html>

我正在解析json文件并在字典中存储值,现在想在创建的html文件中插入这些值。

import json
#from lxml import etree

with open('ninjs_basic.json','r') as file:
    resp_str = file.read()
#print(resp_str)
resp_dict = json.loads(resp_str)

with open('result.html','w') as output:
    output.write('uri: ' + resp_dict['uri']+ '\n')
    output.write(resp_dict['headline'] + '\n')
    output.write(resp_dict['body_text'])

我尝试使用以下代码,但没有运气。这里正确的方法是什么?

python html json html-parsing lxml
1个回答
0
投票

为您提供使用SimplifiedDoc的示例。

from simplified_scrapy import SimplifiedDoc,req,utils
import json
html ='''
<body>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title>#Want to insert dictionary values here in python></title>
  <LINK href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<img src="forkit.gif" id="octocat" alt="" />
<!-- Feel free to change this text here -->
<p>
   #Want to insert dictionary values here in python>
   <placeholder1 />
</p>
<p>
  #Want to insert dictionary values here in python>
  <placeholder2 />
</p>
</body>
</html>'''
doc = SimplifiedDoc(html)

# with open('ninjs_basic.json','r') as file:
#     resp_str = file.read()
# resp_dict = json.loads(resp_str)

with open('result.html','w') as output:
    doc.title.setContent("The title you took from the JSON file")
    doc.placeholder1.repleaceSelf("Want to insert dictionary values here in python")
    doc.placeholder2.repleaceSelf("Want to insert dictionary values here in python")
    output.write(doc.html)
© www.soinside.com 2019 - 2024. All rights reserved.