File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ __author__ = 'luyi'
2+ import os
3+ import urllib .request
4+ import urllib .parse
5+ import json
6+ class weather (object ):
7+ # 获取城市代码的uri
8+ code_uri = "http://apistore.baidu.com/microservice/cityinfo?cityname="
9+ # 获取天气信息的uri
10+ weather_uri = "http://apistore.baidu.com/microservice/weather?cityid="
11+ # 主处理逻辑
12+ def mainHandle (self ):
13+ city_name = input ("输入你要查询的天气:" )
14+ uri = self .code_uri + urllib .parse .quote (city_name )
15+ #获取该城市天气情况的网址
16+ print ("查询中请等待" )
17+ ret = json .loads (urllib .request .urlopen (uri ).read ().decode ("utf8" ))
18+ if ret ['errNum' ] != 0 :
19+ print (ret ['retMsg' ])
20+ return False
21+ #查询失败
22+ else :
23+ #查询成功使用json解析
24+ #需要更详细信息,请看百度api的说明文档。使用方法类似。
25+ weather_uri = self .weather_uri + ret ['retData' ]['cityCode' ]
26+ data = json .loads (urllib .request .urlopen (weather_uri ).read ().decode ("utf8" ))
27+ if data ['errNum' ] == 0 :
28+ ret_data = data ['retData' ]
29+ output = "城市名:" + city_name + "\r \n "
30+ output += "更新时间:" + ret_data ["date" ] + " " + ret_data ["time" ] + "\r \n "
31+ output += "天气:" + ret_data ["weather" ] + " [" + ret_data ["WD" ] + ret_data ["WS" ] + "]\r \n "
32+ output += "当前温度:" + ret_data ["temp" ] + " (" + ret_data ["h_tmp" ] + " ---> " + ret_data ["l_tmp" ] + ")\r \n "
33+ print (output )
34+ return True
35+ else :
36+ print (data ['errMsg' ])
37+ return False
38+ if __name__ == "__main__" :
39+ weather = weather ()
40+ weather .mainHandle ()
41+ a = input ("按任意键退出" )
You can’t perform that action at this time.
0 commit comments