Python+pushpuls+云服务器 自定义微信推送天气预报
小项目目标
(感觉意义在于:手机不常看;在电脑端忙工作时,能在恰当的时候,推送天气预报提醒,便于出行安排)
一、Python获取天气预报信息
1、找寻合适的天气预报网站
天气预报网站很多,找一个较为准确的,页面含有24小时天气预报的, 如:https://www.weaoo.com/shanghai-181282.html
2、Python程序获取天气预报信息
weather_acq.py
import requests from lxml import html def spider(): url = https://www.weaoo.com/shanghai-181282.html # url是爬取地址 resp = requests.get(url) # resp是获得请求数据 resp.encoding = utf-8 # 根据网页的编码方式确定 html_data = resp.text # 获得html页面文本数据 selector = html.fromstring(html_data) ul_list = selector.xpath(//div[@class="mt1 _24hours"]/ul/li) # 根据XPATH路径,确定小时天气预报所在的路径 all = [] # 创建空数组,为了将天气数据打包 for i in range(1, 6): # 个人设置,近5小时的天气预报信息 each_hour = ul_list[i] e_h = html.tostring(each_hour, encoding=utf-8).decode(utf-8) hours = e_h.split(<span)[1].split(>)[1].split(<)[0] weather = e_h.split(<span)[3].split(>)[1].split(<)[0] temperature = e_h.split(<span)[4].split(>)[1].split(<)[0] air = e_h.split(<span)[5].split(")[1] each = hours + , + weather + , + temperature + , + air all.append(each) return all # print all if __name__ == __main__: spider()
运行结果
二、pushplus实现微信推送
1、pushplus(推送加)
-
token:token每个人不一样,能代表你的个人开发、账户、后台 title:用于设置你这条消息的标题,如:上海近5小时天气预报 content:推送的实际内容,如上获取的天气信息 template:设置消息模板类型,如html、txt、md、json等
【注】如果是一对多推送,则还有个topic,用于设置群组编号,让别人扫你的二维码加入群组,消息就能同时发送给别人
2、Python进行内容推送
weather_send.py
import smtplib from email.header import Header from email.mime.text import MIMEText import datetime import weather_acq import requests def send_mails(): now_time = datetime.datetime.now() n_time = str(now_time).split( )[1].split(.)[0] all = weather_acq.spider() # 调用天气预报获取程序,获得数据信息 content_wechat = ("<h4>" + all[0] + "</h4>" + "<br>" + "<h4>" + all[1] + "</h4>" + "<br>" + "<h4>" + all[2] + "</h4>" + "<br>" + "<h4>" + all[3] + "</h4>" + "<br>" + "<h4>" + all[4] + "</h4>") # 对数组数据进行简单处理,弄成html格式 url = http://www.pushplus.plus/send?token=89f932df30554614983812b8036e167a&title=上海天气&content={}&template=html.format(content_wechat) reqp = requests.get(url) if __name__ == __main__: send_mails()
运行结果
三、部署云服务器定时任务
参考下面这篇,可以部署定时运行python程序
四、总结
不足与可改进
-
1、本文挑选的天气预报网站不一定准确 2、内容可以增加,如湿度、适宜情况等 3、可以加适当判断语句,如穿衣提醒、带伞提醒,或仅当未来有雨才推送信息等
注
上一篇:
通过多线程提高代码的执行效率例子