用 Python 写一个天气预报脚本
文章
林里克斯
实验平台:CentOS 7.7.1908
Python Version:3.9.0
1.首先注册 和风天气 账号
2.在应用侧新建一个应用创建 WEB-API
3.完成后会给你一个 KEY
后面需要用到
4.前端显示天气的 HTML
代码
$ vim /data/weather/hefentianqi.html
<div>
<div>
<h1>天气预报</h1>
<h2>贵州省-贵阳市</h2>
</div>
<div>
{% for e_data in data %}
<h3 style="margin:20px auto 10px auto">{{ e_data.date }}</h3>
<div>
<p>
<span>日出时间:</span>
<span>{{ e_data.sr }}</span>
<span style="width:40%margin-left: 30px">日落时间:</span>
<span>{{ e_data.ss }}</span>
</p>
<p>
<span>最高温度:</span>
<span>{{ e_data.tmp_max }}</span>
<span style="width:40%margin-left: 30px">最低温度:</span>
<span>{{ e_data.tmp_min }}</span>
</p>
<p>
<span>风力:</span>
<span>{{ e_data.wind_sc }}</span>
</p>
<p>
<span>降水概率:</span>
<span>{{ e_data['pop'] }}%</span>
</p>
</div>
{% endfor %}
</div>
</div>
5.Python
源码
$ vim /data/weather/weather.py
#!/usr/local/bin/python3
# coding=utf-8
import requests
import json
import smtplib
import jinja2
import os.path as pth
import time
from email.mime.text import MIMEText
from email.header import Header
HEFEN_D = pth.abspath(pth.dirname(__file__))
LOCATION = '贵阳'
ORIGINAL_URL = 'https://free-api.heweather.com/s6/weather/forecast?parameters'
TO = ['mylinux@kjarbo.com']
def sendEmail(content, title, from_name, from_address, to_address, serverport, serverip, username, password):
msg = MIMEText(content, _subtype='html',_charset='utf-8')
msg['Subject'] = Header(title, 'utf-8')
# 这里的to_address只用于显示,必须是一个string
msg['To'] = ','.join(to_address)
msg['From'] = from_name
try:
s = smtplib.SMTP_SSL(serverip, serverport)
s.login(username, password)
# 这里的to_address是真正需要发送的到的mail邮箱地址需要的是一个list
s.sendmail(from_address, to_address, msg.as_string())
print('%s----发送邮件成功' % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
except Exception as err:
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
print(err)
def get_data():
new_data = []
parametres = {
'location': LOCATION,
'key': '*******', #和风天气 KEY
'lang': 'zh',
'unit': 'm'
}
try:
response = requests.get(ORIGINAL_URL,params=parametres)
r = json.loads(json.dumps(response.text,ensure_ascii=False,indent=1))
r = json.loads(response.text)
except Exception as err:
print(err)
weather_forecast = r['HeWeather6'][0]['daily_forecast']
for data in weather_forecast:
new_obj = {}
# 日期
new_obj['date'] = data['date']
# 日出时间
new_obj['sr'] = data['sr']
# 日落时间
new_obj['ss'] = data['ss']
# 最高温度
new_obj['tmp_max'] = data['tmp_max']
# 最低温度
new_obj['tmp_min'] = data['tmp_min']
# 白天天气状况描述
new_obj['cond_txt_d'] = data['cond_txt_d']
# 风向
new_obj['wind_dir'] = data['wind_dir']
# 风力
new_obj['wind_sc'] = data['wind_sc']
# 降水概率
new_obj['pop'] = data['pop']
# 能见度
new_obj['vis'] = data['vis']
new_data.append(new_obj)
return new_data
def render_mail(data):
env = jinja2.Environment(
loader = jinja2.FileSystemLoader(HEFEN_D)
)
return env.get_template('hefentianqi.html').render({'data': data})
def main():
config = {
"from": "mylinux@kjarbo.com",
"from_name": '林里克斯',
"to": TO,
"serverip": "smtp.qq.com",
"serverport": "465",
"username": "mylinux@kjarbo.com",
"password": "*******", #QQ 邮箱授权码
}
title = "天气预报"
data = get_data()
body = render_mail(data)
sendEmail(body, title, config['from_name'], config['from'], config['to'], config['serverport'], config['serverip'], config['username'], config['password'])
main()
6.测试
$ python3 wether.py
2020-11-16 22:14:02----发送邮件成功
7.编写定时任务,每天定时发送邮件
0 22 * * * /usr/local/bin/python3 /data/wether/wether.py >> /data/wether/wether.log 2>&1
Over~
版权协议须知!
本篇文章来源于 Uambiguous ,如本文章侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意
1332 0 2020-11-16
博主卡片
运维时间
搭建这个平台,只为分享及记载自己所遇之事和难题。
现在时间 2024-12-28
今日天气
站点统计
- 文章总数:241篇
- 分类总数:29个
- 评论总数:12条
- 本站总访问量 353826 次
@xiaozi 最后的分享的镜像下载地址打不开 服务器没有开机吗?
@yuanyuan 为什么我的4b安装centos7.9 插上tf卡 显示不兼...
@Wong arrhenius 牛比
@MakerFace 厉害了!
@TongSir 老哥 更新下我的友链链接 https://blog.ton...