Python OpenWeather,JSON-通过城市名称获取天气-如何表示城市名称不正确?

3
我找到并修改了一个简单的Python代码,使用openweather和json格式获取天气状况。但是我有个问题——如果城市名称错误,该如何提示用户?我的意思是,即使我传入一个不存在的城市,程序也总会返回结果(没有“空响应”之类的信息)。
请查看下面的代码以了解我所说的内容:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2, json

city = "etre4t5r5e4re" # the city name is incorrent
url = "http://openweathermap.org/data/2.1/forecast/city?q="
url += city
try :
    request = urllib2.Request(url)
    response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
    info = wx.MessageBox(u"Internet connection error", u"Error", wx.OK | wx.ICON_ERROR)
except urllib2.URLError, e:
    info = wx.MessageBox(u"Internet connection error", u"Error", wx.OK | wx.ICON_ERROR)
except httplib.HTTPException, e:
    info = wx.MessageBox(u"Internet connection error", u"Error", wx.OK | wx.ICON_ERROR)
except Exception:
    info = wx.MessageBox(u"Error", u"Error", wx.OK | wx.ICON_ERROR)
weather = response.read()

if __name__ == '__main__':
    print(weather) # it will show weather but thats not what I want for non-existing city!

1
这个网址 http://openweathermap.org/data/2.1/forecast/city?q=etre4t5r5e4re 对我来说返回了 Internal Server Error Undefined index: geonames_id - Niclas Nilsson
1
当我尝试获取错误的城市信息时,该服务会返回莫斯科。 - alexvassel
@NiclasNilsson:你试过用我的脚本做同样的事情吗(我的意思是运行它)?你得到了什么结果?你能检查一下吗?:) - mazix
@alexvassel:更改了代码:city = str(raw_input("请输入您的城市:\n> ")),但无论我输入什么,都会有一个答案 :/ - mazix
你可能会发现我的GitHub Python项目PyOWM(https://github.com/csparpa/pyowm)很有用,它是一个简单的面向对象的客户端封装,可以调用Open Weather Map Web API。 - csparpa
显示剩余9条评论
1个回答

1

当请求的城市不存在时,会出现重复的ID,您可以基于此编写代码或进行第二次请求。我已经解释了我将要使用的两种解决方案。

#!/usr/bin/python

import urllib2, json

city = "etre4t5r5e4re"
root = "http://openweathermap.org/data/2.1/forecast/city?q=%s"
url  = root % city

response = urllib2.urlopen(url)
j = json.load(response)

# Solution 1
if j.get('url', '').split('/')[-1] == '7284885':
    print " ! This city seems to be THE Unknown city"

# Solution 2
if 'No station' in urllib2.urlopen(j.get('url')).read():
    print " ! Again.. This city seems to be THE Unknown city"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接