有问题。写了代码。一切正常。但是,如果您输入的不是城市,而是任何单词,则脚本会因错误而崩溃。
from pyowm import OWM
from pyowm.utils.config import get_default_config
config_dict = get_default_config()
config_dict['language'] = 'ru' # your language here
owm = OWM('api-key') # You MUST provide a valid API key
place = input("Введи Город/страну: ")
mgr = owm.weather_manager()
observation = mgr.weather_at_place(place)
w = observation.weather
temp = w.temperature('celsius')["temp"]
print("В городе " + place + " Сейчас " + str(w.detailed_status))
print("Температура: " + str(temp))
抛出错误:
Traceback (most recent call last):
File "C:\python\weather.py", line 18, in <module>
observation = mgr.weather_at_place(place)
File "C:\Users\x\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyowm\weatherapi25\weather_manager.py", line 53, in weather_at_place
_, json_data = self.http_client.get_json(OBSERVATION_URI, params=params)
File "C:\Users\x\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyowm\commons\http_client.py", line 143, in get_json
HttpClient.check_status_code(resp.status_code, resp.text)
File "C:\Users\x\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyowm\commons\http_client.py", line 288, in check_status_code
raise exceptions.NotFoundError('Unable to find the resource')
pyowm.commons.exceptions.NotFoundError: Unable to find the resource
当然,您可以尝试检查所有缩写词,当且仅当它们合适时,才抛出请求,但这仍然不是这种情况。根据文档,我发现当请求“weather_at_place”时,会返回“Observation”(我对数据的理解)或“None”(如果现在没有数据)。在其他情况下,会引发数据解析器错误(据我了解):ParseResponseException when OWM Weather API response' data cannot be parsed
那么问题来了,如何不让脚本崩溃,并且在调用解析器错误时,脚本写了类似“错误城市”之类的东西?
版本:Python 3.8.5 pyowm 3.0.0 OS Win10 pro