我有一个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'])
我尝试使用以下代码,但没有运气。这里正确的方法是什么?
为您提供使用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)