|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 观测者 于 2017-5-19 09:01 编辑
- import urllib.request, json
- city_name = input('请输入城市:')
- #获取城市对应的代码
- with open('city.txt', 'r', encoding='utf-8') as f:
- lines = f.readlines()
- for line in lines:
- if city_name in line:
- city_code = line.split('=')[0].strip()
-
- url = ('https://api.heweather.com/x3/weather?cityid=CN%s&key=50246ea62fbd405c9315e51d2a1d29c0' %city_code)
- response = urllib.request.urlopen(url)
- weather_html = response.read()
- json_data = json.loads(weather_html)
- data = json_data['HeWeather data service 3.0'][0]
- #获取PM2.5的值
- pm25 = data['aqi']['city']['pm25']
- #获取空气质量
- air_quality = data['aqi']['city']['qlty']
- #获取城市
- city = data['basic']['city']
- #获取现在的天气、温度、体感温度、风向、风力等级
- now_weather = data['now']['cond']['txt']
- now_tmp = data['now']['tmp']
- now_fl = data['now']['fl']
- now_wind_dir = data['now']['wind']['dir']
- now_wind_sc = data['now']['wind']['sc']
- #今天的天气
- today = data['daily_forecast'][0]
- weather_day = today['cond']['txt_d']
- weather_night = today['cond']['txt_n']
- tmp_high = today['tmp']['max']
- tmp_low = today['tmp']['min']
- wind_dir = today['wind']['dir']
- wind_sc = today['wind']['sc']
- #天气建议
- #舒适度
- comf = data['suggestion']['comf']['brf']
- comf_txt = data['suggestion']['comf']['txt']
- #流感指数
- flu = data['suggestion']['flu']['brf']
- flu_txt = data['suggestion']['flu']['txt']
- #穿衣指数
- drsg = data['suggestion']['drsg']['brf']
- drsg_txt = data['suggestion']['drsg']['txt']
- weather_forcast_txt = '''%s今天白天天气: %s\n夜间天气: %s\n最高气温: %s摄氏度\n最低气温: %s摄氏度
- 风力: %s\n风向: %s\n天气舒适度:%s\n%s\n流感指数: %s\n%s 穿衣指数: %s\n%s 现在外面的天气: %s\n当前温度: %s\n当前风力: %s'''%(city,weather_day,weather_night,tmp_high,tmp_low,wind_sc,wind_dir,comf,comf_txt,flu,flu_txt,drsg,drsg_txt,now_weather,now_tmp,now_wind_sc)
- print(weather_forcast_txt)
-
复制代码
如果输入北京:
- UnicodeEncodeError: 'ascii' codec can't encode character '\ufeff' in position 25: ordinal not in range(128)
复制代码
如果输入乌鲁木齐等某些城市:
- 请输入城市:乌鲁木齐
- Traceback (most recent call last):
- File "C:\Users\观测者\Desktop\项目一:天气预报\weather_forecast.py", line 20, in <module>
- pm25 = data['aqi']['city']['pm25']
- KeyError: 'aqi'
复制代码
而以上城市在api上是可以请求到的,求解。
用的和风天气api。
本帖最后由 zxszx4 于 2017-5-19 10:12 编辑
你的api根本就没有调用成功,乌鲁木齐的那个调用的代码对应的其实是乌鲁木齐牧试站 的id“101130108”,而这个id在api里是没有的。
第二个事是,你的北京的city.txt里最开始是有字符的,大概3个字节的样子。是"ef bb bf"我查了下是Unicode签名BOM,你手动删了这3个字节或者你转成无BOM格式的就可以了。
对了,你的key我也保存了份哈,如果有意见我可以选择忘掉。
额,还有个事,我看了官方文档,给出的城市列表和链接是
https://cdn.heweather.com/china-city-list.txt
里面确实没有乌鲁木齐牧试站
|
|