python feedparser与yahoo天气rss

2024-06-17 12:45:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用feedparser从yahoos天气rss获取一些数据。feed parser似乎剥离了yweather命名空间数据:

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完全忽略了这一点。有去拿的吗?在


Tags: 数据comhttpparserfeed命名rss天气
2条回答

为了完整起见,feedparser也支持这一点。一般语法是名称空间前缀下划线标记名(例如,yweather_条件)。在

在给定的Yahoo weather示例中,可以执行以下操作:

import feedparser
d=feedparser.parse('http://weather.yahooapis.com/forecastrss?w=24260013&u=c')
print (d['items'][0]['yweather_condition'])

收益率

^{pr2}$

文档位于http://www.feedparser.org/docs/namespace-handling.html

以下是使用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的部分可能特别有用。在

相关问题 更多 >