4行Python代码获取指定城市天气预报

101020100是城市的代码,我们只需要找到其他城市的代码,将101020100替换成相应的代码即可。查找方法是,在中国天气网的首页,搜索城市的名称,地址栏中会显示相应城市的代码。如下所示:

使用Python获取天气预报,我们的主要任务在于找到相应的API,解决字符集编码问题。当这些问题解决以后,直接使用requests库获取天气预报即可。下面是获取所在城市天气预报的4行Python代码:

# 获取指定城市天气
 import requests
 r = requests.get('http://www.weather.com.cn/data/sk/101020100.html')
 r.encoding = 'utf-8'
 print r.json()['weatherinfo']['city'], r.json()['weatherinfo']['WD'], r.json()['weatherinfo']['temp']
结果:上海 东风 15

猜你喜欢

转载自blog.csdn.net/weixin_42459823/article/details/91952223