2010-05-20 102 views

回答

0

這裏有一種方法,你可以得到使用使用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的部分可能是特別有幫助。

0

爲了完整起見,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'} 

該文檔是在http://www.feedparser.org/docs/namespace-handling.html