python查天气预报_Python编写一个天气预报查询系统

15393268546734e06d9b75e

学了Python这么久 可以用它来做许多好玩的小程序哦! 这里给 大家做了个查询天气预报的小程序! 可以查询未来几天的天气! 需要大家自己修改下代码即可!

首先我们需要建立一个字典dict 用来存放城市编码! 因为API接口是根据城市编码来查询的 ! 由于城市编码比较多 2600多行 所有不在这里发了! 需要的可以自行百度去下载哦!

15393269799972f31e00712

我们再来分析下api接口 http://t.weather.sojson.com/api/weather/city/101010100

{"time":"2018-10-12 08:00:56","cityInfo":{"city":"北京市","cityId":"101010100","parent":"北京","updateTime":"07:44"},"date":"20181012","message":"Success !","status":200,"data":{"shidu":"74%","pm25":13.0,"pm10":45.0,"quality":"优","wendu":"5","ganmao":"各类人群可自由活动","yesterday":{"date":"11日星期四","sunrise":"06:19","high":"高温 18.0℃","low":"低温 5.0℃","sunset":"17:43","aqi":36.0,"fx":"西南风","fl":"<3级","type":"晴","notice":"愿你拥有比阳光明媚的心情"},"forecast":[{"date":"12日星期五","sunrise":"06:20","high":"高温 20.0℃","low":"低温 8.0℃","sunset":"17:41","aqi":53.0,"fx":"南风","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"},{"date":"13日星期六","sunrise":"06:21","high":"高温 20.0℃","low":"低温 8.0℃","sunset":"17:40","aqi":73.0,"fx":"西南风","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"},{"date":"14日星期日","sunrise":"06:22","high":"高温 22.0℃","low":"低温 10.0℃","sunset":"17:38","aqi":95.0,"fx":"西南风","fl":"<3级","type":"晴","notice":"愿你拥有比阳光明媚的心情"},{"date":"15日星期一","sunrise":"06:23","high":"高温 19.0℃","low":"低温 10.0℃","sunset":"17:37","aqi":61.0,"fx":"东北风","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"},{"date":"16日星期二","sunrise":"06:24","high":"高温 20.0℃","low":"低温 9.0℃","sunset":"17:35","aqi":54.0,"fx":"北风","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"}]}}

返回的是一个json 我们用 requests_html库 get请求即可 这个库是自带json()的!

1539327151494c3d3ad9b91

好了 废话不多说了 我们还是直接上代码吧! 如有不足的地方欢迎指出!还请大神勿喷!

from requests_html import HTMLSession

from city import city

session = HTMLSession()

def weather(cs):

dm = city(cs)

headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'

}

url = 'http://t.weather.sojson.com/api/weather/city/%s' % dm

r = session.get(url, headers=headers)

#r.encoding = r.apparent_encoding

r = r.json()

try:

print(r['time'] + r['cityInfo']['city'])

for i in r['data']['forecast'][0]:

print(r['data']['forecast'][0][i])

except:

print('查询失败!请确认城市名称是否正确!')

if __name__ == '__main__':

while True:

print('*' * 7 + '小七天气预报查询!(输入0退出!)' + '*' * 7)

cs = input('请输入城市名称: ')

if cs != '0':

weather(cs)

else:

print('欢迎再次使用!\n已经退出天气查询!')

break