基于Python实现定时自动给微信好友发送天气预报


Posted in Python onOctober 25, 2018

效果图

基于Python实现定时自动给微信好友发送天气预报

from wxpyimport *
import requests
from datetimeimport datetime
import time
from apscheduler.schedulers.blockingimport BlockingScheduler#定时框架
bot = Bot(cache_path=True)
tuling = Tuling(api_key=你的api')#机器人api
def send_weather(location):
#准备url地址
path ='http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'
url = path % location
response = requests.get(url)
result = response.json()
#如果城市错误就按照濮阳发送天气
if result['error'] !=0:
location ='濮阳'
url = path % location
response = requests.get(url)
result = response.json()
str0 = ('  早上好!这是今天的天气预报!……机器人:PyChatBot\n')
results = result['results']
# 取出数据字典
data1 = results[0]
# 取出城市
city = data1['currentCity']
str1 ='  你的城市: %s\n' % city
# 取出pm2.5值
pm25 = data1['pm25']
str2 ='  Pm值  : %s\n' % pm25
# 将字符串转换为整数 否则无法比较大小
if pm25 =='':
pm25 =0
pm25 =int(pm25)
# 通过pm2.5的值大小判断污染指数
if 0 <= pm25 <35:
pollution ='优'
elif 35 <= pm25 <75:
pollution ='良'
elif 75 <= pm25 <115:
pollution ='轻度污染'
elif 115 <= pm25 <150:
pollution ='中度污染'
elif 150 <= pm25 <250:
pollution ='重度污染'
elif pm25 >=250:
pollution ='严重污染'
str3 ='  污染指数: %s\n' % pollution
result1 = results[0]
weather_data = result1['weather_data']
data = weather_data[0]
temperature_now = data['date']
str4 ='  当前温度: %s\n' % temperature_now
wind = data['wind']
str5 ='  风向  : %s\n' % wind
weather = data['weather']
str6 ='  天气  : %s\n' % weather
str7 ='  温度  : %s\n' % data['temperature']
message = data1['index']
str8 ='  穿衣  : %s\n' % message[0]['des']
str9 ='  我很贴心: %s\n' % message[2]['des']
str10 ='  运动  : %s\n' % message[3]['des']
str11 ='  紫外线 : %s\n' % message[4]['des']
str = str0 + str1 + str2 + str3 + str4 + str5 + str6 + str7 + str8 + str9 + str10 + str11
return str
#好友列表
my_friends = []
my_friends = bot.friends()
my_friends.pop(0)
#发送函数
def send_message():
#给全体好友发送
for friendin my_friends:
friend.send(send_weather(friend.city))
#发送成功通知我
bot.file_helper.send(send_weather('濮阳'))
bot.file_helper.send('发送完毕')
#定时器
print('star')
sched = BlockingScheduler()
sched.add_job(send_message,'cron',month='1-12',day='1-31',hour=5,minute =30)
sched.start()

具体操作:

首先导入wxpy、图灵机器人和定时器Apscheduler,定时器用来定时群发。

具体pip操作建议百度。

使用百度的一个天气接口得到json数据。

主要思路:

1.从wxpy获取好友列表

2.创建定时器

3.定时器触发函数

4.函数执行,遍历好友列表

5.好友对象执行带参函数,参数为该好友城市

6.函数中请求百度天气接口,得到该好友对应天气数据,解析处理数据,发送天气信息,完成该对象发送。

7.遍历结束,发送完毕

缺陷:打包为exe文件之后启动失败,原因是定时器找不到trigger,要想解决需要查看Apscheduler相关资料。

解决方法:换一种定时器。

编译器上正常执行。

打包为exe之后,可以很方便发给别人使用。扫码登录后每天早上5:30会自动给所有好友发送效果图中的天气预报。

PS:下面看下Python实现微信定时发送天气预报

schedule实现定时

import requests
from requests import exceptions
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
from wxpy import *
import schedule
import time
bot=Bot(cache_path=True) #登陆网页微信,并保存登陆状态
def sendblogmsg(content):
  #搜索自己的好友,注意中文字符前需要+u
  my_friend = bot.friends().search(u'卿尘')[0]
  my_friend.send(content)
  #my_group = bot.groups().search(u'卿尘')[0]
  #my_group.send(content) #发送天气预报
def job():
  resp=urlopen('http://www.weather.com.cn/weather/101010100.shtml')
  soup=BeautifulSoup(resp,'html.parser')
  tagToday=soup.find('p',class_="tem") #第一个包含class="tem"的p标签即为存放今天天气数据的标签
  try:
    temperatureHigh=tagToday.span.string #有时候这个最高温度是不显示的,此时利用第二天的最高温度代替。
  except AttributeError as e:
    temperatureHigh=tagToday.find_next('p',class_="tem").span.string #获取第二天的最高温度代替
  temperatureLow=tagToday.i.string #获取最低温度
  weather=soup.find('p',class_="wea").string #获取天气
  contents = '北京' + '\n' + '最高温度:' + temperatureHigh + '\n' + '最低温度:' + temperatureLow + '\n' + '天气:' + weather 
    # result3 = '最低温度:' + temperatureLow
  #print('最低温度:' + temperatureLow)
  #print('最高温度:' + temperatureHigh)
  # print('天气:' + weather)
  sendblogmsg(contents)
#定时
schedule.every().day.at("19:20").do(job) #规定每天12:30执行job()函数
while True:
  schedule.run_pending()#确保schedule一直运行
  time.sleep(1)
bot.join() #保证上述代码持续运行

end

总结

以上所述是小编给大家介绍的基于Python实现定时自动给微信好友发送天气预报,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
Python内置函数dir详解
Apr 14 Python
Python3 Post登录并且保存cookie登录其他页面的方法
Dec 28 Python
python的几种矩阵相乘的公式详解
Jul 10 Python
python3 批量获取对应端口服务的实例
Jul 25 Python
学习和使用python的13个理由
Jul 30 Python
Python3 解决读取中文文件txt编码的问题
Dec 20 Python
TensorFlow tf.nn.conv2d实现卷积的方式
Jan 03 Python
python实现删除列表中某个元素的3种方法
Jan 15 Python
Python面向对象程序设计之静态方法、类方法、属性方法原理与用法分析
Mar 23 Python
python报错TypeError: ‘NoneType‘ object is not subscriptable的解决方法
Nov 05 Python
python爬虫之selenium库的安装及使用教程
May 23 Python
还在手动盖楼抽奖?教你用Python实现自动评论盖楼抽奖(一)
Jun 07 Python
python批量修改图片后缀的方法(png到jpg)
Oct 25 #Python
python bmp转换为jpg 并删除原图的方法
Oct 25 #Python
virtualenv 指定 python 解释器的版本方法
Oct 25 #Python
解决python3读取Python2存储的pickle文件问题
Oct 25 #Python
python 解压pkl文件的方法
Oct 25 #Python
纯用NumPy实现神经网络的示例代码
Oct 24 #Python
Django添加KindEditor富文本编辑器的使用
Oct 24 #Python
You might like
基于PHP文件操作的详解
2013/06/05 PHP
php最简单的删除目录与文件实现方法
2014/11/28 PHP
利用百度地图JSAPI生成h7n9禽流感分布图实现代码
2013/04/15 Javascript
jquery删除ID为sNews的tr元素的内容
2014/04/10 Javascript
浅析javascript的间隔调用和延时调用
2014/11/12 Javascript
跟我学习javascript的函数和函数表达式
2015/11/16 Javascript
jQuery双向列表选择器DIV模拟版
2016/11/01 Javascript
Javascript for in的缺陷总结
2017/02/03 Javascript
AngularJS 防止页面闪烁的方法
2017/03/09 Javascript
浅谈Angular2 模块懒加载的方法
2017/10/04 Javascript
React Native使用fetch实现图片上传的示例代码
2018/03/07 Javascript
利用vue.js把静态json绑定bootstrap的table方法
2018/08/28 Javascript
vue自定义指令实现方法详解
2019/02/11 Javascript
如何在JavaScript中谨慎使用代码注释
2019/06/21 Javascript
关于layui 弹出层一闪而过就消失的解决方法
2019/09/09 Javascript
vue中使用element ui的弹窗与echarts之间的问题详解
2019/10/25 Javascript
详解elementUI中input框无法输入的问题
2020/04/27 Javascript
Vue实现可移动水平时间轴
2020/06/29 Javascript
javascript实现图片轮换动作方法
2020/08/07 Javascript
详解nginx配置vue h5 history去除#号
2020/11/09 Javascript
python实现登陆知乎获得个人收藏并保存为word文件
2015/03/16 Python
python用模块zlib压缩与解压字符串和文件的方法
2016/12/16 Python
Python进阶-函数默认参数(详解)
2017/05/18 Python
通过Pandas读取大文件的实例
2018/06/07 Python
python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)
2019/04/01 Python
在jupyter notebook中调用.ipynb文件方式
2020/04/14 Python
打印tensorflow恢复模型中所有变量与操作节点方式
2020/05/26 Python
Python csv文件记录流程代码解析
2020/07/16 Python
Python实现一个论文下载器的过程
2021/01/18 Python
东方电视购物:东方CJ
2016/10/12 全球购物
秋季运动会通讯稿
2014/01/24 职场文书
2014年酒店服务员工作总结
2014/12/08 职场文书
产品质量保证书范本
2015/02/27 职场文书
Pytorch可视化的几种实现方法
2021/06/10 Python
php修改word的实例方法
2021/11/17 PHP
利用Python实时获取steam特惠游戏数据
2022/06/25 Python