아이디어는 모든 형제 태그를 찾아 중지 find_next_siblings()
를 사용하여 다음 텍스트로 strong
태그를 찾을 수 있습니다 : 여기
Adresa: Obecný úrad Nána, Madáchova 32, 943 60 Nána
코드의 예입니다 다음 strong
태그에 :
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup, NavigableString
data = u"""
<p>
<strong>Adresa:</strong>Obecný úrad Nána<br></br>Madáchova 32<br></br>943 60 Nána<br></br><br></br>
<strong>Telefón:</strong>036/759 70 06<br></br>
<strong>Fax:</strong>036/7597 007<br></br>
<strong>Web:</strong><a href="http://www.obecnana.sk"></a><br></br>
</p>
"""
soup = BeautifulSoup(data)
address = soup.find(text='Adresa:')
texts = []
for item in address.parent.find_next_siblings():
if item.name == 'strong':
break
text_before = item.previous_sibling
if isinstance(text_before, NavigableString):
texts.append(text_before)
print ' '.join(texts)
그것은 인쇄 :
그것은 인쇄 할
print get_section_text('Adresa:')
print get_section_text('Telefón:')
print get_section_text('Fax:')
:
Obecný úrad Nána Madáchova 32 943 60 Nána
그런 다음, 당신은 좋은 재사용 가능한 기능에 코드를 추출 할 수 있습니다 :
def get_section_text(text):
section = soup.find(text=text)
if not section:
raise ValueError("Section not found")
texts = []
for item in section.parent.find_next_siblings():
if item.name == 'strong':
break
text_before = item.previous_sibling
if isinstance(text_before, NavigableString):
texts.append(text_before)
return ' '.join(texts)
그리고 다른 부분에 대한 호출
Obecný úrad Nána Madáchova 32 943 60 Nána
036/759 70 06
036/7597 007
존재하지 않는 부분에 대한
는 :
print get_section_text('ILLEGAL SECTION')
그것은 당신이 문자열을 축적, 볼 다음 <strong>
태그까지 <strong>Adresa:</strong>
태그의 형제 자매 반복하는 next_sibling
을 사용할 수 있습니다
ValueError: Section not found
난 당신이 기본적으로()'여기'find_next_siblings을 개혁하는 것 같아요. – alecxe
나는 이렇게 생각하지만,이 특정 응용 프로그램에 대해 나에게 더 간결 해 보인다. – mhawke