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

十年热恋 提交于 2020-01-05 06:50:48

问题


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

回答1:


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']



回答2:


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.



来源:https://stackoverflow.com/questions/13306438/how-can-i-get-xml-attributes-and-values-from-an-rss-feed-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!