forked from kuri65536/python-for-android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweather.py
More file actions
44 lines (32 loc) · 1.26 KB
/
weather.py
File metadata and controls
44 lines (32 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""Retrieve the weather report for the current location."""
__copyright__ = 'Copyright (c) 2009, Google Inc.'
__license__ = 'Apache License, Version 2.0'
import string
import urllib
import urllib2
from xml.dom import minidom
WEATHER_URL = 'http://www.google.com/ig/api?weather=%s&hl=%s'
def extract_value(dom, parent, child):
"""Convenience function to dig out weather values."""
return dom.getElementsByTagName(parent)[0].getElementsByTagName(child)[0].getAttribute('data')
def fetch_weather(location, hl=''):
"""Fetches weather report from Google
Args:
location: a zip code (94041); city name, state (weather=Mountain View,CA);...
hl: the language parameter (language code)
Returns:
a dict of weather data.
"""
url = WEATHER_URL % (urllib.quote(location), hl)
handler = urllib2.urlopen(url)
data = handler.read()
dom = minidom.parseString(data)
handler.close()
data = {}
weather_dom = dom.getElementsByTagName('weather')[0]
data['city'] = extract_value(weather_dom, 'forecast_information','city')
data['temperature'] = extract_value(weather_dom, 'current_conditions','temp_f')
data['conditions'] = extract_value(weather_dom, 'current_conditions', 'condition')
dom.unlink()
return data