01 前言
最近武漢的天氣越來越惡劣了。動不動就下雨,所以,擁有一款好的天氣預報工具,對於我們大學生來說,還真是挺重要的了。好了,自己動手,豐衣足食,我們來用Python打造一個天氣預報的微信機器人吧。

02 效果展示
后台登錄

收到天氣預報消息:

03 環境配置
Python版本:3.6.0
系統平台:Windows 10 X64
相關模塊:
json模塊;
requests模塊;
itchat模塊;
以及一些Python自帶的模塊。
04 獲取天氣
主要原理很簡單,找一個天氣的API接口(這里我們使用的是http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?
),使用requests發起請求,接受返回的結果,用python中內置的包json. 將json字符串轉換為python的字典或列表,然后從字典中取出數據。
具體可以看代碼:
1 city = input('請輸入要查詢的城市名稱:')
2
3 url = 'http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'%city
4 # 使用requests發起請求,接受返回的結果
5 rs = requests.get(url)
6 # 使用loads函數,將json字符串轉換為python的字典或列表
7 rs_dict = json.loads(rs.text)
8 # 取出error
9 error_code = rs_dict['error']
10 # 如果取出的error為0,表示數據正常,否則沒有查詢到結果
11 if error_code == 0:
12 # 從字典中取出數據
13 results = rs_dict['results']
14 # 根據索引取出天氣信息字典
15 info_dict = results[0]
16 # 根據字典的key,取出城市名稱
17 city_name = info_dict['currentCity']
18 # 取出pm值
19 pm25 = info_dict['pm25']
20 print('當前城市:%s pm值:%s'%(city_name,pm25))
21 # 取出天氣信息列表
22 weather_data = info_dict['weather_data']
23 # for循環取出每一天天氣的小字典
24 for weather_dict in weather_data:
25 # 取出日期,天氣,風級,溫度
26 date = weather_dict['date']
27 weather = weather_dict['weather']
28 wind = weather_dict['wind']
29 temperature = weather_dict['temperature']
注釋很明了。相信大家都能get it!
05 發送天氣預報
在獲取到天氣預報的數據以后,接下來就是通過itchat模塊把信息發送到我們的微信上面了。原理也很簡單,先掃碼登錄我們的微信機器人,然后通過備注名獲取要發送的好友,send過去就OK啦。
具體看下面代碼:
1 # nickname = input('please input your firends\' nickname : ' )
2 # 想給誰發信息,先查找到這個朋友,name后填微信備注即可
3 # users = itchat.search_friends(name=nickname)
4 users = itchat.search_friends(name='起風了') # 使用備注名來查找實際用戶名
5 # 獲取好友全部信息,返回一個列表,列表內是一個字典
6 print(users)
7 # 獲取`UserName`,用於發送消息
8 userName = users[0]['UserName']
9 itchat.send(date+weather+wind+temperature, toUserName=userName)
說說怎么實現每天定時預報:
可以在程序加個while(True),然后每天定時獲取天氣,send過去。當然,你最好有一天雲主機,把程序掛在主機上面就OK。
另一種實用的思路是:
收取消息關鍵字,然后回復天氣。這個給大家思考實現啦。
06 完整代碼
欲獲取代碼,請關注我們的微信公眾號【程序猿聲】,在后台回復:pycode04。即可獲取。

推薦文章:10分鍾教你用Python做個打飛機小游戲超詳細教程
推薦文章:10分鍾教你用python下載和拼接微信好友頭像圖片