小朋友们好,大朋友们好!
我是猫妹,一名爱上Python编程的小学生。
欢迎和猫妹一起,趣味学Python。
今日主题
如何用Python,根据天气API,获取未来天气信息呢?
之前wxpy库好用,可以通过它将天气预报信息推给关心的微信好友。
在使用这个库的时,有遇到报错,网友提到这个库好久没更新了,不建议使用它。
因此,咱们今天就省略了将获取到的天气预报信息推送给好友步骤,直接手动复制、粘贴、发送就行。
天气API接口
我们怎么知道当地城市的未来天气呢?
这个信息是通过向第三方平台请求来获得的。
比如
你问它某个城市某天的天气如何?
网站会返回,被查询城市的某天天气。
比如,在浏览器输入如下信息:
http://t.weather.sojson.com/api/weather/city/101020100
你会看到:

这里返回的就是上海未来五天的天气情况,用Python解析后的结果如下:

很多小伙伴不在上海,怎么查询所在城市的天气呢?
或者小伙伴在上海,但想查询上海具体到某个区的天气,怎么查询呢?
只需要修改下city_code即可,即把101020100(上海)改成你所要查询城市的city_code。
怎么获取当地城市或地区的city_code呢?
可以搜索下。
如果没查到,或者懒得查询,也可以看同名公号(和猫妹学Python)的此条。
猫妹把400多个city_code放在此条了。
公.众.号(和猫妹学Python)的此条了,447条city_code。
Python解析数据
Python擅长数据处理,向服务器请求数据,拿到数据,解析数据。
这些对Python来说,小菜一碟!
把返回的Json格式数据,解析成咱人类容易阅读的格式。
仅此而已,最后,猫妹把调试好的代码分享下:
import requestsfrom wxpy import *import jsondef get_weather(url):r=requests.get(url)data=json.loads(r.text)city = data['cityInfo']['city']weather=data['data']['forecast']return city,weatherdef get_content_send(city,weather):all_day=[]content_send=""for i in range(0,6,1):content=weather[i]every_day=[]every_day.append(city+"天气情况:")every_day.append(content['ymd']+' '+content ['week'])every_day.append(content['high']+' '+content['low'])every_day.append(content['fx']+':'+content['fl'])every_day.append(content['type']+'AQI:'+str(content['aqi']))every_day.append(content['notice'])all_day.append(every_day)for i in range(0,6,1):for data in all_day[i]:content_send = content_send+data+'\n'content_send=content_send+'\n'return content_senddef send_content(content_send):bot =Bot(cache_path=True)my_friend =bot.friends().search('和猫妹学Python')[0]my_friend.send(content_send)if __name__ == '__main__':url ='http://t.weather.sojson.com/api/weather/city/101020100'city,weather=get_weather(url)content_send=get_content_send(city,weather)#send_content(content_send)print('********************')print(content_send)
怎么样?
你调通了吗?

好了,我们今天就学到这里吧!
如果遇到什么问题,咱们多多交流,共同解决。
我是猫妹,咱们下次见!

被折叠的 条评论
为什么被折叠?



