0

こんにちは私はPythonのminidomモジュールを理解するのに苦労しています。

私は次のようなxmlを持っています:

<Show>
<name>Dexter</name>
<totalseasons>7</totalseasons>
<Episodelist>
<Season no="1">
<episode>
<epnum>1</epnum>
<seasonnum>01</seasonnum>
<prodnum>101</prodnum>
<airdate>2006-10-01</airdate>
<link>http://www.tvrage.com/Dexter/episodes/408409</link>
<title>Dexter</title>
</episode>
<episode>
<epnum>2</epnum>
<seasonnum>02</seasonnum>
<prodnum>102</prodnum>
<airdate>2006-10-08</airdate>
<link>http://www.tvrage.com/Dexter/episodes/408410</link>
<title>Crocodile</title>
</episode>
<episode>
<epnum>3</epnum>
<seasonnum>03</seasonnum>
<prodnum>103</prodnum>
<airdate>2006-10-15</airdate>
<link>http://www.tvrage.com/Dexter/episodes/408411</link>
<title>Popping Cherry</title>
</episode>

もっときれい:http ://services.tvrage.com/feeds/episode_list.php?sid = 7926

そして、これはそれから読み取ろうとしている私のPythonコードです:

xml = minidom.parse(urlopen("http://services.tvrage.com/feeds/episode_list.php?sid=7926"))
for episode in xml.getElementsByTagName('episode'):
    for node in episode.attributes['title']:
        print node.data

各エピソードからすべてのデータを取得したいので、実際のエピソードデータを取得できません。さまざまなバリエーションを試しましたが、動作させることができません。ほとんど私は<DOM Element: asdasd>戻ってきます。私は各エピソード内のデータのみを気にします。

助けてくれてありがとう

4

3 に答える 3

1

title属性ではなく、タグです。属性src<img src="foo.jpg" />

>>> parsed = parseString(s)
>>> titles = [n.firstChild.data for n in parsed.getElementsByTagName('title')]
>>> titles
[u'Dexter', u'Crocodile', u'Popping Cherry']

上記を拡張して、他の詳細を取得できます。lxmlただし、これには適しています。上記のスニペットからわかるように、minidom はそれほど友好的ではありません。

于 2012-09-09T12:21:42.330 に答える
1

episode要素には、要素を含む子要素がありtitleます。ただし、コードは代わりに属性を探しています。

minidom 要素からテキストを取得するには、ヘルパー関数が必要です。

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)

そして、すべてのタイトルをより簡単に印刷できます。

for episode in xml.getElementsByTagName('episode'):
    for title in episode.getElementsByTagName('title'):
        print getText(title)
于 2012-09-09T12:22:53.560 に答える
0

ElementTree API を教えてくれた Martijn Pieters のおかげで、この問題は解決しました。

xml = ET.parse(urlopen("http://services.tvrage.com/feeds/episode_list.php?sid=7296"))
                print 'xml fetched..'
                for episode in xml.iter('episode'):
                    print episode.find('title').text

ありがとう

于 2012-09-09T12:24:16.657 に答える