Python openweather,json - 通过城市名称获取天气 - 我怎么说这个城市是不正确的?

问题描述:

我找到并修改了简单的代码,以便使用openweather和json格式在Python中获取天气状况。但我有一个问题 - 我怎么说这个城市是不正确的?Python openweather,json - 通过城市名称获取天气 - 我怎么说这个城市是不正确的?

我的意思是,即使我通过一个错误的,不存在的城市,阅读总是给出一个答案(theres没有这样的事情像'空回应'或类似的东西)。

请参见下面的代码,看看我说的是:

#!/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

的URL通过'http://openweathermap.org/data/2.1/forecast/city Q = etre4t5r5e4re'返回'内部服务器错误未定义指数:geonames_id'我。 –

+1

当我试图得到不正确的城市信息时,该服务给了我莫斯科。 – alexvassel

+0

@NiclasNilsson:奇怪,因为我实际上得到这个输出:http://pastebin.com/aa1q6DBK没有错误o_O – mazix

有要求时,这个城市不存在复发的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"