витягуємо погоду з Yahoo Weather на Python'і

import re
import urllib
from xml.dom import minidom
from pprint import pprint
from datetime import datetime

WEATHER_URL = 'http://weather.yahooapis.com/forecastrss?w=%s&u=c'
WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'

def weather_for_location(location_id):
    url = WEATHER_URL % location_id
    dom = minidom.parse(urllib.urlopen(url))
    forecasts = []
    for node in dom.getElementsByTagNameNS(WEATHER_NS, 'forecast'):
        forecasts.append({
            'date': node.getAttribute('date'),
            'low': node.getAttribute('low'),
            'high': node.getAttribute('high'),
            'condition': node.getAttribute('text'),
        })
    ycondition = dom.getElementsByTagNameNS(WEATHER_NS, 'condition')[0]
    ywind = dom.getElementsByTagNameNS(WEATHER_NS, 'wind')[0]
    yatmosphere = dom.getElementsByTagNameNS(WEATHER_NS, 'atmosphere')[0]
    yastronomy = dom.getElementsByTagNameNS(WEATHER_NS, 'astronomy')[0]
    ydescription = dom.getElementsByTagName('description')[1].firstChild.data
    patImgSrc = re.compile('src="(.*)".*/>')

    return {
        'current_condition': ycondition.getAttribute('text'),
        'current_temp': ycondition.getAttribute('temp'),
        'current_humidity': yatmosphere.getAttribute('humidity'),
        'current_visibility': yatmosphere.getAttribute('visibility'),
        'current_sunrise': yastronomy.getAttribute('sunrise'),
        'current_sunset': yastronomy.getAttribute('sunset'),
        'current_wind_speed': ywind.getAttribute('speed'),
        'current_wind_chill': ywind.getAttribute('chill'),
        'current_wind_direction': ywind.getAttribute('direction'),
        'current_img': re.findall(patImgSrc, ydescription),
        'forecasts': forecasts,
        'title': dom.getElementsByTagName('title')[0].firstChild.data,
        'guid': dom.getElementsByTagName('guid')[0].firstChild.data,
        }

2 коментарі:

Unknown сказав...

А виклик ф-ції? :)
print weather_for_location('924943')

g7v сказав...

угу, ID своє треба визначити додатково.