-
Notifications
You must be signed in to change notification settings - Fork 0
/
GetBaiduWeather.py
43 lines (42 loc) · 1.68 KB
/
GetBaiduWeather.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# -*- coding: utf-8 -*-
#!/usr/bin/python
# coding=utf-8
# Python 2.7.3
# File: GetBaiduWeather.py
import os
import urllib.request
import urllib.parse
import json
class weather(object):
# 获取城市代码的uri
code_uri = "http://apistore.baidu.com/microservice/cityinfo?cityname="
# 获取天气信息的uri
weather_uri = "http://apistore.baidu.com/microservice/weather?cityid="
# 主处理逻辑
def mainHandle(self):
print("输入你要查询的天气:")
city_name = input()
uri = self.code_uri + urllib.parse.quote(city_name)
ret = json.loads(urllib.request.urlopen(uri).read().decode("utf8"))
if ret['errNum'] != 0:
print(ret['retMsg'])
return False
else:
weather_uri = self.weather_uri + ret['retData']['cityCode']
data = json.loads(urllib.request.urlopen(weather_uri).read().decode("utf8"))
if data['errNum'] == 0:
ret_data = data['retData']
output = "城市名:" + city_name + "\r\n"
output += "更新时间:" + ret_data["date"] + " " + ret_data["time"] + "\r\n"
output += "天气:" + ret_data["weather"] + " [" + ret_data["WD"] + ret_data["WS"] + "]\r\n"
output += "当前温度:" + ret_data["temp"] + " (" + ret_data["h_tmp"] + " ---> " + ret_data["l_tmp"] + ")\r\n"
print(output)
return True
else:
print(data['errMsg'])
return False
if __name__ == "__main__":
reload(sys)
sys.setdefaultencoding('utf8')
weather = weather()
weather.mainHandle()