jinja2模板引擎:
pip install jinja2
一。jinja2语法:
1.一般变量<li>hello {{name}}</li>
2.{#普通列表#}
{% for user in users %}
<li>hello {{user}}</li>
{% endfor %}
{#字典列表#}
{% for userinfo in userinfos %}
<li>总个数:{{loop.length}}</li>
<li>{{loop.index}}</li>
<li>{{userinfo.username}}:{{userinfo.password}}</li>
{% endfor %}
3.{#if else的使用#}
{% if user=='feiyu1009' %}
<li>hello feiyu1009</li>
{% else %}
<li>sorry not you!!</li>
{% endif %}
二。简单使用
1.首先建立templ文件夹,建立模板文件temp.html,内容:
<html>
<head>
<title>temp1</title>
</head>
<body>
{{name}}
{#普通列表#}
{% for user in users %}
<li>hello {{user}}</li>
{% endfor %}
{#字典列表#}
{% for userinfo in userinfos %}
<li>总个数:{{loop.length}}</li>
<li>{{loop.index}}</li>
<li>{{userinfo.username}}:{{userinfo.password}}</li>
{% endfor %}
</body>
</html>
2.jinja_demo.py
# jinja_demo1
import sys
from jinja2 import PackageLoader, Environment, FileSystemLoader
# sys.path.append('../..')
# 1.packageloader
# env = Environment(loader=PackageLoader('demo1', 'templete'))
# template = env.get_template('temp.html')
# content=template.render(name='visitor')
# 2.FilesystemLoader 列表变量,字典变量
env = Environment(loader=FileSystemLoader('../templete'))
template = env.get_template('temp2.html')
content = template.render(users=['黄飞鸿', '霍元甲'],userinfos=[{"username":'feiyu1009',"password":'888888'},
{"username":'feiyu3009',"password":'888888'}])
#生成html文件
with open('temp2_result.html', 'w') as f:
f.write(content)
三。实战。抓取本人简书首页文字列表并生成html
temp文件内容temp2.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>temp2</title>
</head>
<body>
<table>
<tr><th>序号</th><th>标题</th></tr>
{% for url in urls %}
<tr>
<td>{{loop.index}}</td>
<td><a href="{{url.href}}">{{url.title}}</a></td>
</tr>
{% endfor %}
</table>
</body>
</html>
py文件:jinja_demo2.py
from jinja2 import PackageLoader, Environment, FileSystemLoader
from bs4 import BeautifulSoup as BS
def get_data():
base_url = "https://www.jianshu.com"
#懒得安装selnium了,直接把首页的源码赋值到本地解析了
with open(r'D:\python\sample\demo1\字符串文本处理\jianshu.html', 'r', encoding='utf-8') as f:
res = f.read()
soup = BS(res, 'lxml')
print(soup.select('a.title'))
for a in soup.select('a.title'):
yield {"href": base_url + a['href'],
"title": a.text
}
if __name__ == '__main__':
urls = []
for i in get_data():
urls.append(i)
print(urls)
env = Environment(loader=FileSystemLoader('../templete'))
template = env.get_template('temp2.html')
content = template.render(urls=urls)
with open('res0701.html', 'w') as f:
f.write(content)
执行后生成html:
image.png
网友评论