1

以下のコードに埋め込まれている YouTube の xml を解析しようとしています。すべてのタイトルを表示しようとしています。ただし、「タイトル」の入力行のみを印刷しようとすると、問題が発生します。何かアドバイス?

#import library to do http requests:
import urllib2

#import easy to use xml parser called minidom:
from xml.dom.minidom import parseString
#all these imports are standard on most modern python implementations

#download the file:
file = urllib2.urlopen('http://gdata.youtube.com/feeds/api/users/buzzfeed/uploads?v=2&max-results=50')
#convert to string:
data = file.read()
#close file because we dont need it anymore:
file.close()

#parse the xml you downloaded
dom = parseString(data)
entry=dom.getElementsByTagName('entry')
for node in entry:
    video_title=node.getAttribute('title')
    print video_title
4

3 に答える 3

1

タイトルは属性ではなく、エントリの子要素です。

これを抽出する方法の例を次に示します。

for node in entry:
    video_title = node.getElementsByTagName('title')[0].firstChild.nodeValue
    print video_title
于 2012-10-08T16:47:58.657 に答える
0

コードに小さなバグがあります。titleはentryの子要素ですが、属性としてアクセスします。コードは次の方法で修正できます。

dom = parseString(data)
for node in dom.getElementsByTagName('entry'):
    print node.getElementsByTagName('title')[0].firstChild.data
于 2012-10-08T17:05:20.983 に答える
0

lxmlを理解するのは少し難しいので、ここに非常にシンプルな美しいスープのソリューションを示します (理由により、beautifulsoup と呼ばれています)。lxml パーサーを使用するように美しいスープを設定することもできるため、速度はほぼ同じです。

from bs4 import BeautifulSoup
soup = BeautifulSoup(data) # data as is seen in your code
soup.findAll('title')

title要素のリストを返します。この場合、要素 (実際のビデオ名) soup.findAll('media:title')だけを返すために使用することもできます。media:title

于 2012-10-08T16:23:25.563 に答える