这是用python写的天气查询代码,可用。
这里用的是和风天气的接口
参考:http://www.heweather.com/documents/dev-sample#python
我用的城市数据:http://download.csdn.net/detail/yabaj/9432163
将城市数据存放本地:
jsons = {这里是城市数据}
import pickle
pickle_file = open('city_data.pkl', 'wb')
pickle.dump(jsons, pickle_file)
pickle_file.close()
import urllib.request
import json
import pickle
from datetime import date
city1 = []
city2 = []
num = ''#城市编码
def loadData():
pickle_file = open('city_data.pkl', 'rb')
global city1
city1 = pickle.load(pickle_file)
def init():
loadData()
while 1:
flag = 0
p = input('请输入省:')
for each in city1:
if each['省'] == p:
flag = 1
global city2
city2 = each['市']
break
if flag == 0:
print ('输入的省不存在!')
continue
else:
while 1:
c = input('请输入城市:')
for each in city2:
if each['市名'] == c:
flag = 0
global num
num = each['编码']
break
if flag == 1:
print ('输入的城市不存在!')
continue
else:
return
while 1:
init()
url = 'https://api.heweather.com/x3/weather?cityid=CN' + num + '&key=自己的key值'
data = None
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
req = urllib.request.Request(url, data, headers=headers)
weatherHTML = urllib.request.urlopen(req).read().decode('utf-8')# 读入打开的url
fn = str(date.today())+'.txt'
#查询得到的数据存放本地
weather_file = open(fn, 'w')
weather_file.write(weatherHTML)
weather_file.close()
#print (weatherHTML)
weatherJSON = json.loads(weatherHTML)# 创建json
weatherInfo = weatherJSON["HeWeather data service 3.0"]
# 打印信息
print ('城市:', weatherInfo[0]['basic']['city'])
print ('更新时间:', weatherInfo[0]['basic']['update']['loc'])
print ('24小时天气:')
print ('温度:', weatherInfo[0]['daily_forecast'][0]['tmp']['max'], '-', weatherInfo[0]['daily_forecast'][0]['tmp']['min'])
print ('天气:', weatherInfo[0]['daily_forecast'][0]['cond']['txt_d'], ',', weatherInfo[0]['daily_forecast'][0]['cond']['txt_n'])
temp = input ('按任意键继续:')