1:城市-代码对照字典(只列出了部分,其他省略了,不影响说明实现原理).
city={
'北京':'101010100',
'海淀':'101010200'
}
2:存储在文件中的代码:
import pickle
pickle_file=open('city_data.pkl','wb')
pickle.dump(city,pickle_file)
pickle_file.close()
3:查询代码
import urllib.request
import json
import pickle
pickle_file= open('city_data.pkl','rb')
city=pickle.load(pickle_file)
password=input('请输入城市')
name1=city[password]
File1=urllib.request.urlopen('http://www.weather.com.cn/data/sk/'+str(name1)+'.html')
weatherHTML=File1.read().decode("utf-8")
weatherJSON=json.JSONDecoder().decode(weatherHTML)
weatherInfo=weatherJSON['weatherinfo']
#打印信息
print('城市:',weatherInfo['city'])
print('温度:',weatherInfo['temp'])
4:结果
备注:小甲鱼视频中的访问的天气网址失效,可以自己换一下,原理不变。
备用天气网址