2016-10-14 1 views
3

문제가 있습니다. 내 목표는 잠시 동안 데이터를 분석하는 것입니다. 그런 다음 파싱을 중지하고 싶습니다.Beautilful Soup의 어느 지점에서 html을 제거하십시오.

 <span itemprop="address"> 
     Some address 
     </span> 
     <i class="fa fa-signal"> 
     </i> 
     ... 
     </p> 
     </div> 
    </div> 
    <div class="search_pagination" id="pagination"> 
     <ul class="pagination"> 
     </ul> 
    </div> 
    </div> 
    </div> 
    </div> 
    <div class="col-sm-3"> 
    <div class="panel" itemscope="" itemtype="http://schema.org/WPSideBar"> 
    <h2 class="heading_a" itemprop="name"> 
    Top-10 today 
    </h2> #a lot of tags after that moment 

나는 순간 Top-10 today 때까지 (그 중 많은 앞에있다) <span itemprop="address">에서 모든 값을 얻을 싶어요. 당신이 생각 후 "톱 10"오늘 어떤 전에 약간의 "주소"를 가지고 있지만 당신이 그것을하기 전에 오는 사람들에 관심이 있다면

from bs4 import BeautifulSoup, SoupStrainer 

only_addresses = SoupStrainer("span", itemprop="address") 
soup = BeautifulSoup(html_doc, "html.parser", parse_only=only_addresses) 

, 당신은 할 수 있습니다 :

답변

0

당신은 실제로 BeautifulSoupparse only the tags you are interested in via SoupStrainer가하도록 할 수 있습니다 사용자 정의 searching function는 :

def search_addresses(tag): 
    return tag.name == "span" and tag.get("itemprop") == "address" and \ 
      tag.find_next("h2", text=lambda text: text and "Top-10 today" in text) 

addresses = soup.find_all(search_addresses) 

그것은 사소한 보이지 않는,하지만 아이디어는 간단하다 - 우리는 "상위 10 오늘"제목이 뒤에 존재 여부를 확인하기 위해 모든 "주소"를 find_next()을 사용하고 있습니다.

관련 문제