4

Python を使用して XML ファイルを解析し、XML フィードからタイトル、作成者、URL、および概要を取得しようとしています。次に、データを収集している XML が次のようになっていることを確認します。

<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
  xmlns:grddl="http://www.w3.org/2003/g/data-view#"
  grddl:transformation="2turtle_xslt-1.0.xsl">

<title>Our Site RSS</title>
<link href="http://www.oursite.com" />
<updated>2013-08-14T20:05:08-04:00</updated>
<id>urn:uuid:c60d7202-9a58-46a6-9fca-f804s879f5ebc</id>
<rights>
    Original content available for non-commercial use under a Creative
    Commons license (Attribution-NonCommercial-NoDerivs 3.0 Unported),
    except where noted.
</rights>

<entry>
    <title>Headline #1</title>
    <author>
        <name>John Smith</name>
    </author>
    <link rel="alternate"
          href="http://www.oursite.com/our-slug/" />
    <id>1234</id>
    <updated>2013-08-13T23:45:43-04:00</updated>

    <summary type="html">
        Here is a summary of our story
    </summary>
</entry>
<entry>
    <title>Headline #2</title>
    <author>
        <name>John Smith</name>
    </author>
    <link rel="alternate"
          href="http://www.oursite.com/our-slug-2/" />
    <id>1235</id>
    <updated>2013-08-13T23:45:43-04:00</updated>

    <summary type="html">
        Here is a summary of our second story
    </summary>
</entry>

私のコードは次のとおりです。

import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()

for child in root:
    print child.tag

Python が child.tag を出力するとき、タグは「エントリ」ではなく「{ http://www.w3.org/2005/Atom }エントリ」です。私は使用しようとしました:

for entry in root.findall('entry'):

しかし、エントリのタグにはルート タグの一部である w3 url が含まれているため、これは機能しません。また、root の孫を取得すると、そのタグは "{ http://www.w3.org/2005/Atom }author"として表示されます。

XML を変更することはできませんが、root.findall('entry') が機能するように変更 (ルートを単に に設定) して再保存するか、コードを変更するにはどうすればよいですか?

4

2 に答える 2

5

これは ElementTree の標準的な動作です。検索するタグが名前空間内で宣言されている場合、それらのタグを検索するときにその名前空間を指定する必要があります。ただし、次のようなことができます。

import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()

def prepend_ns(s):
    return '{http://www.w3.org/2005/Atom}' + s

for entry in root.findall(prepend_ns('entry')):
    print 'Entry:'
    print '    Title: '   + entry.find(prepend_ns('title')).text
    print '    Author: '  + entry.find(prepend_ns('author')).find(prepend_ns('name')).text
    print '    URL: '     + entry.find(prepend_ns('link')).attrib['href']
    print '    Summary: ' + entry.find(prepend_ns('summary')).text
于 2013-08-15T01:19:02.663 に答える
1

BeautifulSoup4 を試してみてください。XML だけでなく、HTML なども解析できる非常に強力なツールです。

from bs4 import BeautifulSoup

def main():
    input = """....""" 
    soup = BeautifulSoup(input)   
    for entry in soup.findAll("entry"):
        title = entry.find("title").text.strip()
        author = entry.find("author").text.strip()
        link  = entry.find("link").text.strip()
        summary = entry.find("summary").text.strip()
        print title, author, link, summary
if __name__ == '__main__':
    main()
于 2013-08-15T01:28:27.570 に答える