当前位置: 首页 > 后端技术 > Python

使用python获取天气接口发送天气预报给指定的微信好友

时间:2023-03-25 19:44:20 Python

先看效果图:使用的模块:PyMySQLrequeststhreadingwxpy实现上面的例子,首先有两个地方获取天气信息和发送天气通过微信获取天气信息有几个需要注意的小点。获取天气信息获取天气信息的接口获取天气信息的城市获取我们所在城市的城市代码如果我们把天气情况发给多人,这些人来自不同的城市,那么我们是不可能进入每次城市名称,然后查找城市代码,然后访问接口获取天气情况。这样会很麻烦,所以我们需要考虑把城市名和城市代码一一对应起来。一一对应,第一个想到的数据结构就是字典,那么我们可以将这些信息存储在字典中,然后持久化到文件中,这样就方便多了。首先我们得到最新的城市表,是一个列表类型,一般格式如下:[{"id":1,"pid":0,"city_code":"101010100","city_name":"北京","post_code":"100000","area_code":"010","ctime":"2019-07-1117:30:06"},{"id":2,"pid":0,"city_code":"","city_name":"安徽","post_code":null,"area_code":null,"ctime":null}]我们简单的粘贴复制放到一个空列表中,如下图,将所有城市信息放入列表citycodecitycode=[{"id":1,"pid":0,"city_code":"101010100","city_name":"北京","post_code":"100000","area_code":"010","ctime":"2019-07-1117:30:06"},.............................{“id”:2,“pid”:0,“city_code”:“无”,"city_name":"安徽","post_code":"null","area_code":"null","ctime":"null"}]cityinfo={}#将城市名称和城市代码写入json文件open('city_for_code.json','w',encoding='utf-8')asf:foriincitycode:name=i["city_name"]code=i["city_code"]cityinfo[name]=代码f.write(str(cityinfo))#测试是否可以用open('city_for_code.json','r+',encoding='utf-8')asfile:data_dst=file.readlines()d=eval(data_dst[0])然后就是一站式处理,把city_name和city_code这两个我们需要的字段取出来,然后写入到文件中即可。读的话,按照上面的方法读就可以了。需要注意的是,使用open()方法读取文件,获取的内容是一个列表,我们需要通过eval()方法将其转化为dict类型。这就是把city_name和city_code放到一个文件里,我们也可以把它们放到一个数据库里。这里以MySQL为例,安装PyMySQL模块importpymysqldb_parames={'host':'localhost','user':'root','password':'123456','database':'city_code_info'}#Connect到数据库conn=pymysql.connect(**db_parames)#创建游标对象,增删改查都在游标上cursor=conn.cursor()#如果表存在则删除cursor.execute("DROPTABLEIFEXISTScity_code")#Buildtablestatementcreate_table_sql="""CREATETABLE`city_code`(`city_name`varchar(20)DEFAULTNULL,`city_code`varchar(25)DEFAULTNULL)ENGINE=InnoDBDEFAULTCHARSET=utf8mb4;"""#建表cursor.execute(create_table_sql)#Insertdatawithopen('city_for_code.json','r+',encoding='utf-8')asf:origin_data=f.readlines()current_data=eval(origin_data[0])#读取的内容是只包含一个元素的列表#print(current_data.get('北京','不存在。'))forname,codeincurrent_data.items():sql="""INSERTINTOcity_code(city_name,city_code)VALUES('%s','%s')"""%(name,code)try:cursor.execute(sql)除了:conn.rollback()conn.commit()conn.close()执行这个python程序,将文件中的城市名称和城市代码保存到库中。当然,我们也可以直接获取城市名称和城市代码,然后跳过文件持久化的步骤,直接把这两个字段取出来存入,但是考虑到代码需要多练习多写,所以是多余的下面是输入城市名称获取城市代码的代码块:importpymysqldefget_city_code(city_name):db_parames={'host':'localhost','user':'root','password':'123456','database':'city_code_info'}#连接数据库conn=pymysql.connect(**db_parames)#创建游标对象,在游标上进行增删改查cursor=conn.cursor()#Create查询语句select_sql="SELECT*FROMcity_codewherecity_name='%s'"%(city_name)try:cursor.execute(select_sql)result=cursor.fetchall()forrowinresult:city_code=row[1]returncity_codeexcept:return"Error:unabletofetchdata!"然后根据输入的城市代码获取天气:importrequestsdefget_weather(city_name,get_date_time=3):city_code=get_city_code(city_name)url='http://t.weather.sojson.com/api/weather/city/%s'%(city_code)header={'user-agent':'Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/74.0.3729.169野生动物园/537。36'}response=requests.get(url,header)response.encoding='utf-8'weather=response.json()day={1:'明天',2:'后天',3:'大后天'}weather_lst=[]fornuminrange(get_date_time):City=weather["cityInfo"]["city"]Weatherganmao=weather["data"]["ganmao"]Weatherquality=weather["data"]["quality"]Weathershidu=weather["data"]["shidu"]Weatherwendu=weather["data"]["wendu"]Weatherpm25=str(weather["data"]["pm25"])Weatherpm10=str(weather["data"]["pm10"])Dateymd=weather["data"]["forecast"][num]["ymd"]Dateweek=weather["data"]["forecast"][num]["week"]Sunrise=weather["data"]["forecast"][num][“日出”]日落=天气[“数据”][“预测”][num][“日落”]Windfx=天气[“数据”][“预测”][num][“fx”]Windf1=weather["data"]["forecast"][num]["fl"]Weathertype=weather["data"]["forecast"][num]["type"]Weathernotice=weather["data"][“预测”][num][“通知”]Weatherhigh=weather["data"]["forecast"][num]["high"]Weatherlow=weather["data"]["forecast"][num]["low"]ifnum==0:result='今天??的天气预报'+'\n'\+'Date:'+Dateymd+''+Dateweek+''+City+'\n'\+'Weather:'+Weathertype+''+Windfx+''+windf1+''+Weathernotice+'\n'\+'当前温度:'+Weatherwendu+'℃'+'\n'\+'空气湿度:'+Weathershidu+'\n'\+'温度范围:'+Weatherlow+''+'~'+''+Weatherhigh+'\n'\+'污染指数:'+'PM2.5:'+Weatherpm25+''+'PM10:'+Weatherpm10+'\n'\+'空气质量:'+Weatherquality+'\n'\+'日出时间:'+日出+'\n'\+'日落时间:'+日落+'\n'\+'温馨提示:'+Weatherganmaoelse:which_day=day.get(num,'outofrange')result='\n'+which_day+''+'天气预报'+'\n'\+'Date:'+Dateymd+''+Dateweek+''+City+'\n'\+'Weather:'+Weathertype+''+Windfx+''+Windf1+''+Weathernotice+'\n'\+'温度范围:'+Weatherlow+''+'~'+''+Weatherhigh+'\n'\+'日出时间:'+Sunrise+'\n'\+'日落时间:'+Sunset+'\n'\+'Reminder:'+Weatherganmaoweather_lst.append(result)weather_str=''#因为默认输出三天的天气情况,所以我们需要创建一个空字符串,然后在每次迭代中将天气情况拼接成空字符串字符串formsginweather_lst:weather_str+=msg+'\n'returnweather_str下面是发送微信消息fromwxpyimport*defsend_wx(city_name,who):bot=Bot(cache_path=True)#bot=Bot(console_qr=2、cache_path='botoo.pkl')my_friend=bot.friends().search(who)[0]msg=get_weather(city_name)try:my_friend.send(msg)except:my_friend=bot.friends().search('fei')[0]my_friend.send(u"发送失败")然后我们还需要写一个定时器,每隔一段时间发送一次fromthreadingimportTimerdefauto_send():city_name='设置citytosend'friend_list=['peopletosend']forwhoinfriend_list:send_wx(city_name,who)globaltimertimer=Timer(1,auto_send)timer.start()最后执行程序if__name__=='__main__':timer=Timer(1,auto_send)timer.start()欢迎各位小伙伴关注我的公众号,一起学习进步