2013-12-12 4 views
1

HTTP RSS 웹 페이지를 쿼리하고 수신하여 .txt 파일로 변환하고 minidom을 사용하여 XML 내의 요소를 쿼리 할 수있었습니다.Python을 사용하여 XML 파일을 구문 분석하는 텍스트

다음으로해야 할 일은 내 요구 사항을 충족하는 선택적 링크 목록을 만드는 것입니다. 여기

내 파일에 유사한 구조를 가지고 예제 XML 파일입니다

minidom으로
<xml> 
    <Document name = "example_file.txt"> 
     <entry id = "1"> 
      <link href="http://wwww.examplesite.com/files/test_image_1_Big.jpg"/> 
     </entry> 
     <entry id = "2"> 
      <link href="http://wwww.examplesite.com/files/test_image_1.jpg"/> 
     </entry> 
     <entry id = "3"> 
      <link href="http://wwww.examplesite.com/files/test_image_1_Small.jpg"/> 
     </entry> 
     </entry> 
     <entry id = "4"> 
      <link href="http://wwww.examplesite.com/files/test_image_1.png"/> 
     </entry> 
     <entry id = "5"> 
      <link href="http://wwww.examplesite.com/files/test_image_2_Big.jpg"/> 
     </entry> 
     <entry id = "6"> 
      <link href="http://wwww.examplesite.com/files/test_image_2.jpg"/> 
     </entry> 
     <entry id = "7"> 
      <link href="http://wwww.examplesite.com/files/test_image_2_Small.jpg"/> 
     </entry> 
     </entry> 
     <entry id = "8"> 
      <link href="http://wwww.examplesite.com/files/test_image_2.png"/> 
     </entry> 
    </Document> 
</xml> 

가, 난 그냥 링크 목록에 내려 수 있지만, 나는이 단계의 경우를 건너 뛸 수 있습니다 생각 텍스트 검색 매개 변수를 기반으로 목록을 만들 수 있습니다. 나는 단지이 링크를 원하는 모든 링크를 원하지 않는다 : 파이썬에 새가되는

http://wwww.examplesite.com/files/test_image_1.jpg 
http://wwww.examplesite.com/files/test_image_2.jpg 

을, 나는 ","큰 ", 또는 .PNG을"이없는 경우에만 잡아 링크를 "말을하는 방법을 잘 모르겠습니다 링크 이름에 "작은".

내 최종 목표는 한 번에 파이썬 다운로드이 파일 하나를 가지고하는 것입니다. 목록이 가장겠습니까?

이 더욱 복잡, 내가 제한하고하려면 Python 2.6이 포함 된 주식 라이브러리. 훌륭한 제 3 자 API를 구현할 수 없습니다.

답변

0

012 사용및 cssselect이 쉽다 :

from pprint import pprint 


import cssselect # noqa 
from lxml.html import fromstring 


doc = fromstring(open("foo.html", "r").read()) 
links = [e.attrib["href"] for e in doc.cssselect("link")] 
pprint(links) 

출력 :

links = links[:2] 

이것은 :

['http://wwww.examplesite.com/files/test_image_1_Big.jpg', 
'http://wwww.examplesite.com/files/test_image_1.jpg', 
'http://wwww.examplesite.com/files/test_image_1_Small.jpg', 
'http://wwww.examplesite.com/files/test_image_1.png', 
'http://wwww.examplesite.com/files/test_image_2_Big.jpg', 
'http://wwww.examplesite.com/files/test_image_2.jpg', 
'http://wwww.examplesite.com/files/test_image_2_Small.jpg', 
'http://wwww.examplesite.com/files/test_image_2.png'] 

만 링크 (? 두이 )의 두하려면 파이썬에서 Slicing이라고 불렀습니다.

파이썬에 새로운이기 때문에, 내가 링크 이름의 .PNG ","큰 "또는"작은 "을"이없는 경우에만 잡아 링크를 "말을하는 방법을 잘 모르겠습니다. 어떤 도움이 좋을 것

이 같은 목록을 필터링 할 수 있습니다 : 이것은 당신에게 줄 것이다

doc = fromstring(open("foo.html", "r").read()) 
links = [e.attrib["href"] for e in doc.cssselect("link")] 
predicate = lambda l: not any([s in l for s in ("png", "Big", "Small")]) 
links = [l for l in links if predicate(l)] 
pprint(links) 

:

['http://wwww.examplesite.com/files/test_image_1.jpg', 
'http://wwww.examplesite.com/files/test_image_2.jpg'] 
+0

내가 멀리 얻을 수를 분석하여 사전을 반환합니다.나는 원래 게시물에 나열된 링크 중 두 개만 인쇄하려고합니다. 논리를 적용하여 두 개의 링크로 연결하는 방법을 잘 모르겠습니다. – Michael

+0

답변을 포함하여 업데이트했습니다. –

+0

파이썬을 처음 접했을 때 "링크 이름에".png ","Big "또는"Small "이없는 링크 만 가져 오는 방법을 모르겠다. 어떤 도움도 좋을 것입니다. – Michael

0
import re 
from xml.dom import minidom 

_xml = '''<?xml version="1.0" encoding="utf-8"?> 
<xml > 
    <Document name="example_file.txt"> 
     <entry id="1"> 
      <link href="http://wwww.examplesite.com/files/test_image_1_Big.jpg"/> 
     </entry> 
     <entry id="2"> 
      <link href="http://wwww.examplesite.com/files/test_image_1.jpg"/> 
     </entry> 
     <entry id="3"> 
      <link href="http://wwww.examplesite.com/files/test_image_1_Small.jpg"/> 
     </entry> 
     <entry id="4"> 
      <link href="http://wwww.examplesite.com/files/test_image_1.png"/> 
     </entry> 
     <entry id="5"> 
      <link href="http://wwww.examplesite.com/files/test_image_2_Big.jpg"/> 
     </entry> 
     <entry id="6"> 
      <link href="http://wwww.examplesite.com/files/test_image_2.jpg"/> 
     </entry> 
     <entry id="7"> 
      <link href="http://wwww.examplesite.com/files/test_image_2_Small.jpg"/> 
     </entry> 
     <entry id="8"> 
      <link href="http://wwww.examplesite.com/files/test_image_2.png"/> 
     </entry> 
    </Document> 
</xml> 
''' 

doc = minidom.parseString(_xml) # minidom.parse(your-file-path) gets same resul 
entries = doc.getElementsByTagName('entry') 
link_ref = (
    entry.getElementsByTagName('link').item(0).getAttribute('href') 
    for entry in entries 
) 
plain_jpg = re.compile(r'.*\.jpg$') # regex you needs 
result = (link for link in link_ref if plain_jpg.match(link)) 
print list(result) 

이 코드는 [u'http://wwww.examplesite.com/files/test_image_1_Big.jpg', u'http://wwww.examplesite.com/files/test_image_1.jpg', u'http://wwww.examplesite.com/files/test_image_1_Small.jpg', u'http://wwww.examplesite.com/files/test_image_2_Big.jpg', u'http://wwww.examplesite.com/files/test_image_2.jpg', u'http://wwww.examplesite.com/files/test_image_2_Small.jpg']의 결과를 가져옵니다.

그러나 우리는 xml.etree.ElementTree을 더 잘 사용할 수 있습니다. etree는 빠르고 메모리가 적으며 스마트 한 인터페이스입니다.

etree가 표준 라이브러리에 번들되었습니다.

0
from feedparse import parse 
data=parse("foo.html") 
for elem in data['entries']: 
    if 'link' in elem.keys(): 
     print(elem['link']) 

도서관 "feedparse는"XML 내용

관련 문제