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

How to Insert dictionary values into a html template file using python?

提问人:tec data 提问时间:6/4/2020 最后编辑:tec data 更新时间:6/6/2020 访问量:551

问:

我有一个如下所示的 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 解析 lxml

评论


答:

0赞 dabingsou 6/6/2020 #1

举个使用 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)