python feedparser与雅虎天气rss
问题描述:
我想使用feedparser从yahoos天气rss获取一些数据。它看起来像饲料解析器剥离出来的yweather命名空间数据:python feedparser与雅虎天气rss
http://weather.yahooapis.com/forecastrss?w=24260013&u=c
<yweather:condition text="Fair" code="34" temp="23" date="Wed, 19 May 2010 5:55 pm EDT" />
看起来feedparser完全忽略。有没有拿到它?
答
这里有一种方法,你可以得到使用使用lxml数据:
import urllib2
import lxml.etree
url = "http://weather.yahooapis.com/forecastrss?w=24260013&u=c"
doc = lxml.etree.parse(urllib2.urlopen(url)).getroot()
conditions = doc.xpath('*/*/yweather:condition',
namespaces={'yweather': 'http://xml.weather.yahoo.com/ns/rss/1.0'})
try:
condition=conditions[0]
except IndexError:
print('yweather:condition not found')
print(condition.items())
# [('text', 'Fair'), ('code', '33'), ('temp', '16'), ('date', 'Wed, 19 May 2010 9:55 pm EDT')]
上using xpath with namespaces的部分可能是特别有帮助。
答
为了完整起见,feedparser也支持这一点。一般语法是名称空间前缀下划线标记名称(例如,yweather_condition)。
在给出的雅虎天气例如,一个可以这样做:
import feedparser
d=feedparser.parse('http://weather.yahooapis.com/forecastrss?w=24260013&u=c')
print (d['items'][0]['yweather_condition'])
产生
{'date': u'Mon, 18 Jul 2011 7:53 pm EDT', 'text': u'Fair', 'code': u'34', 'temp': u'27'}