2014-03-28 2 views
0

안녕하세요, python을 사용하여 다음 xml 파일을 구문 분석하고 싶습니다. 내 "폴더"변수는 태그 끝으로 8 자리 숫자와 항상 같도록 설정됩니다. 초 값 :이 경우에는 내가 당량 걸주고, 링크 태그의 마지막 8 자리 같을 때 "폴더"라고 말할 수 있어야합니다 파이썬Python을 사용하여 XML 파일을 구문 분석합니다. multiple hiearchies

for folder in folderList: 

11119709.

입니다 . 나는 python 워드 프로세서 요소 트리에서 제공하는 코드로 놀아 보았지만 너무 많은 계층 구조가 있기 때문에 문제가 있습니다. root [0] [1] .text는 item 태그 아래의 변수를 검색하지 않습니다. 어떤 도움을 주셔서 감사합니다.

(외부 모듈) HTML 및 XML을 구문 분석하고 하나는 파이썬에 포함 된보다 사용하기 방법으로 쉽게 할 수 있습니다 XML

-<rss xmlns:georss="http://www.georss.org/georss/" xmlns:eq="http://earthquake.usgs.gov/rss/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" version="2.0"> 
    -<channel> 
     <title>USGS Earthquake ShakeMaps</title> 
     <description>List of ShakeMaps for events in the last 30 days</description> 
     <link>http://earthquake.usgs.gov/</link> 
     <dc:publisher>U.S. Geological Survey</dc:publisher> 
     <pubDate>Thu, 27 Mar 2014 15:33:05 +0000</pubDate> 
     <item> 
     <title>4.11 - 79.3 miles NNW of Kotzebue</title> 
     <description> 
     <![CDATA[<img src="http://earthquake.usgs.gov/eqcenter/shakemap/thumbs/shakemap_ak_11199709.jpg" width="100" align="left" hspace="10"/><p>Date: Thu, 27 Mar 2014 07:28:31 UTC<br/>Lat/Lon: 67.9858/-163.494<br/>Depth: 15.9122</p>]]></description> 
     <link>http://earthquake.usgs.gov/eqcenter/shakemap/ak/shake/11199709/</link> 
     <pubDate>Thu, 27 Mar 2014 07:53:33 +0000</pubDate> 
     <geo:lat>67.9858</geo:lat> 
     <geo:long>-163.494</geo:long> 
     <dc:subject>4</dc:subject> 
     <eq:seconds>1395905311</eq:seconds> 
     <eq:depth>15.9122</eq:depth> 
     <eq:region>ak</eq:region> 
     </item> 
     <item> 
       ...similar to above item 

답변

0

사용 BeautifulSoup.

이 코드는 당신이 원하는 일을해야합니다 당신은 속도에 대해 걱정하는 경우

from bs4 import BeautifulSoup 

xml = BeautifulSoup(open("filename.xml")) # here you load your XML file 
# you can also load it from an URL by using "urllib" or "Python-Requests" 

# BeautifulSoup(open("filename.xml"), "xml") # if you want to use an XML parser 
# see comments below 

for folder in folderList: 
    for item in xml.findAll("items"): # iterate through all <item> elements 
     if folder in item.link.text: # if folder's name is in the <link> element 
      print(item.find("eq:seconds").text) # print the <eq:seconds> element 
+0

고마워요! 우리 서버 시스템에 beautifulsoup을 설치할 수 있는지 확신 할 수는 없지만 살펴 보겠습니다. – Andrew

+0

@Andrew 셸 (예 : SSH 사용)에 액세스 할 수있는 경우 PIP를 사용하여 쉽게 설치할 수 있습니다 :'pip install beautifulsoup4', PIP가 없다면 스크립트 디렉토리에서 beautifulsoup tarball을 추출 할 수 있습니다. –

+0

BeautifulSoupt는 xml 파서가 아니지만 xml을 파싱하는 데'lxml'을 사용할 수 있습니다. 하지만 이렇게하려면 생성자에 [xml "인수] (http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser)를 전달해야합니다. 그렇지 않으면 xml이 아닌 html 파서를 사용하여 파싱 된 내용입니다. – mata

1

, 나는 lxml하는 것이 좋습니다. 추가 종속성이 있지만 일반적으로 BeautifulSoup보다 훨씬 빠릅니다.

관련 문제