sarbo
sarbo

Reputation: 1691

How can I get XML attributes and values from an RSS feed in Python?

I'm using the Yahoo! Weather API to retrieve some values. This is the request:

Los Angeles Weather

How can I get attributes and values from the following:

<yweather:astronomy sunrise="6:20 am" sunset="4:52 pm"/>
<yweather:condition text="Partly Cloudy" code="29" temp="14" date="Fri, 09 Nov 2012 1:47 am PST"/>

I want to print something like:

Sunrise: 6.20 am
Sunset: 4.52 pm

Upvotes: 1

Views: 383

Answers (2)

James Henstridge
James Henstridge

Reputation: 43899

You can do this using the feedparser library:

import feedparser

feed = feedparser.parse('http://weather.yahooapis.com/forecastrss?w=2442047&u=c')
print 'Sunrise:', feed.feed.yweather_astronomy['sunrise']
print 'Sunset:', feed.feed.yweather_astronomy['sunset']

Upvotes: 3

user647772
user647772

Reputation:

Use feedparser:

import feedparser

feed = feedparser.parse('http://weather.yahooapis.com/forecastrss?w=2442047&u=c')
sunrise = feed.items()[0][1]["yweather_astronomy"]["sunrise"]
sunset = feed.items()[0][1]["yweather_astronomy"]["sunset"]

Play with the result of parse to get a feeling for the structure of the parsed feed.

Upvotes: 2

Related Questions