2012-11-10 61 views
0

我正在嘗試返回視頻的持續時間,但遇到問題。如何爲特定條目解析youtube xml?

#YOUTUBE FEED 
#download the file: 
file = urllib2.urlopen('http://gdata.youtube.com/feeds/api/videos/2s0vk2wEMtA') 
#convert to string: 
data = file.read() 
#close file because we dont need it anymore: 
file.close() 

#entire feed 
root = etree.fromstring(data) 

for entry in root: 
    for item in entry: 
     print item 

當我打印的項目,我所看到的是最後一個元素:

Element '{http://gdata.youtube.com/schemas/2007}duration' at 0x10c4fb7d0 

但我不知道怎麼去從這個值。有什麼建議?

回答

0

media = root.find('{http://search.yahoo.com/mrss/} group') length = media.find('{http://gdata.youtube.com/schemas/2007 } duration()'attrib.get(「seconds」) 打印長度

+0

需要注意的是,使用json返回數據更簡單,更清晰。例如,看看這個URL,你會看到提取持續時間有多容易。我知道的代碼大塊大塊的評論看起來很醜陋,但你可以使用: '進口JSON 進口的urllib2 urlfile = urllib2.urlopen('http://gdata.youtube.com/feeds/api/videos/ 2s0vk2wEMtA?v = 2&ALT = jsonc') jsonString = urlfile.read() urlfile.close() jsonData = json.loads(jsonString) 打印jsonData [ 「數據」] [ 「持續時間」]' – Jeff