2013-06-13 3 views
0

Python에는 XML 및 HTML 파서가 많이 있으며, HTML 문서의 섹션을 추출하는 간단한 방법을 찾고 있습니다. XPATH 구문을 사용하는 것이 좋지만 선택 사항 일뿐입니다. 여기 Python에서 HTML 문서의 특정 요소를 구문 분석하고 추출하는 방법은 무엇입니까?

src = "<html><body>...<div id=content>AAA<B>BBB</B>CCC</div>...</body></html>" 

내가 ID = 내용으로 요소의 몸 전체를 추출 할 예, 그래서 결과는 다음과 같아야합니다 <div id=content>AAA<B>BBB</B>CCC</div>

내가없이 할 수 있다면 그것은 것 새 라이브러리를 설치하는 중입니다.

원하는 요소의 원래 내용을 가져 오는 것이 좋습니다 (다시 포맷되지 않음).

regexp는 XML/HTML 구문 분석에 안전하지 않으므로 사용할 수 없습니다.

답변

1

라이브러리를 사용하여 구문 분석하려면 - 가장 좋은 방법은 BeautifulSoup 입니다. 다음은 어떻게 작동하는지 보여줍니다.

from BeautifulSoup import BeautifulSoup 

src = "<html><body>...<div id=content>AAA<B>BBB</B>CCC</div>...</body></html>" 
soupy = BeautifulSoup(src) 

content_divs = soupy.findAll(attrs={'id':'content'}) 
if len(content_divs) > 0: 
    # print the first one 
    print str(content_divs[0]) 

    # to print the text contents 
    print content_divs[0].text 

    # or to print all the raw html 
    for each in content_divs: 
     print each 
0

그래,이 작업을 수행했습니다. 가장 좋은 방법은 아닐지 모르지만 아래 코드처럼 작동합니다. 나는 이것을 테스트하지 않았다.

import re 

match = re.finditer("<div id=content>",src) 
src = src[match.start():] 

#at this point the string start with your div everything proceeding it has been stripped. 
#This next part works because the first div in the string is the end of your div section. 
match = re.finditer("</div>",src) 
src = src[:match.end()] 

src는 이제 문자열에서 div를 갖는다. 당신이 원하는 것을 내부에 다른 상황이있는 경우 당신은 당신을 위해 더 멋진 검색 패턴을 만들어야 할 것입니다.

+0

후손을 위해 : http://stackoverflow.com/a/1732454/326736 – Kalyan02

관련 문제