2013-08-15 2 views
1

XML 파일을 구문 분석하여 XML 피드의 제목, 작성자, URL 및 요약을 가져 오려고합니다. 그럼 우리가 데이터를 수집하는 XML을 보장하는 것은 다음과 같이이다 :잘못된 태그가있는 Python ElementTree로 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 

대신에 태그가 "항목"존재의 태그는 { "입니다 http://www.w3.org/2005/Atom} entry "로 끝납니다. 나는 다음을 사용하려고 시도했다 :

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

그러나 입력 태그에 루트 태그의 일부인 w3 url이 포함되어 있기 때문에 작동하지 않습니다. 또한 루트의 손자에게 "{http://www.w3.org/2005/Atom} author"라고 표시된 태그를 표시합니다.

XML을 변경할 수 없지만이를 어떻게 수정할 수 있습니까? (루트 만 설정) 다시 저장하거나 root.findall ('entry') 코드가 작동하도록 코드를 작성 하시겠습니까?

답변

2

이것은 표준 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 
+0

조셉, 정말 고마워요! 나는 내가 쉽게 무언가를 놓치고 있다는 것을 알았다. – user1703361

0

이 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()