【发布时间】:2012-11-25 13:03:49
【问题描述】:
我找到并修改了简单的代码,以使用 openweather 和 json 格式在 Python 中获取天气状况。但我有一个问题——我怎么能说城市不正确呢?
我的意思是,即使我经过一个错误的、不存在的城市,阅读也总会给出答案(没有“空响应”之类的东西)。
请参阅下面的代码以了解我在说什么:
#!/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!
【问题讨论】:
-
网址
http://openweathermap.org/data/2.1/forecast/city?q=etre4t5r5e4re为我返回Internal Server Error Undefined index: geonames_id。 -
当我尝试获取不正确的城市信息时,该服务会显示莫斯科。
-
@NiclasNilsson:这很奇怪,因为我实际上得到了这个输出:pastebin.com/aa1q6DBK 没有错误 o_O
-
@alexvassel 也感谢您的回答,非常有帮助。至少我知道这个脚本不仅我有错误的结果
-
@mazix: 真奇怪pastebin.com/LH8dATfL
标签: python json weather weather-api