通过地点获取当前天气的Python代码
有没有一种简单易用的Python代码,可以输入一个地点,然后返回天气信息?最好是免费的。现在用屏幕抓取的方法已经不太好用了,因为服务器会随机改变它们的HTML类名和div标签名,以防止这种行为。
我试过这个方法,它是有效的,但免费的使用额度有限制。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import urllib.request
import sys
import json
API_KEY = "YOUR_API_KEY"
city_name = "Seattle%20Washington%20USA"
try:
ResultBytes = urllib.request.urlopen(
"http://api.weatherstack.com/current?access_key=" + \
str(API_KEY) + "&query=" + str(city_name))
jsonData = json.load(ResultBytes)
locationStanza = jsonData.get('location', None)
currentStanza = jsonData.get('current', None)
cityname = str(locationStanza['name'])
regionname = str(locationStanza['region'])
country = str(locationStanza['country'])
location_val = str(cityname) + " " + str(regionname) + " " + str(country)
time_val = str(currentStanza['observation_time'])
info_val = str(currentStanza['weather_descriptions'][0])
centigrade_value = str(currentStanza['temperature'])
print(centigrade_value)
except urllib.error.HTTPError as e:
ErrorInfo= e.read().decode()
print('Error code: ', e.code, ErrorInfo)
sys.exit()
except urllib.error.URLError as e:
ErrorInfo= e.read().decode()
print('Error code: ', e.code,ErrorInfo)
sys.exit()
1 个回答
2
使用 svn checkout http://python-weather-api.googlecode.com/svn/trunk/ python-weather-api-read-only
可以从 python-weather-api 下载代码。
我在用ubuntu系统,如果你用的是其他操作系统,可以查看链接里的说明。
进入 python-weather-api-read-only
文件夹,然后运行 sudo python setup.py install
来安装。
你可以从 这里 获取天气国家代码的ID。
我根据文档的例子写了一个简单的函数:
import pywapi
import string
def get_weather(loc_id):
weather_com_result = pywapi.get_weather_from_weather_com(loc_id)
yahoo_result = pywapi.get_weather_from_yahoo(loc_id)
print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in Galway Ireland.\n\n"
print "Yahoo says: It is " + string.lower(yahoo_result['condition']['text']) + " and " + yahoo_result['condition']['temp'] + "C now in Galway Ireland.\n\n"
In [2]: get_weather('EIXX0017')
Weather.com says: It is cloudy / windy and 11C now in Galway Ireland.
Yahoo says: It is partly cloudy and 12C now in Galway Ireland.
我花了五分钟在谷歌上查找、安装并写出一个简单的函数。
如果你想接受用户输入,可以创建一个字典,把国家/城市作为键,把代码作为值存储。