2016-09-14 4 views
0

를 사용하여 긴 태그에서 일부 텍스트를 얻기 위해, 나는 다음과 같이 HTML 코드에서 한 brandname 및 제품 이름을 추출 할 :는 어떻게 쇼핑 웹 사이트를 공부하고있다 BeautifulSoup로

<h1 class="product-name elim-suites">Chantecaille<span itemprop="name" >Limited Edition Protect the Lion Eye Palette</span></h1>

results = soup.findAll("h1", {"class" : "product-name elim-suites"})[0].text

을 얻은 : 나는 시도 당신이 볼 수 있듯이 u'ChantecailleLimited Edition Protect the Lion Eye Palette'

는, 샹트 칼리는 한 brandname이며, 나머지는 제품 이름이지만, 그들은 이제 서로 어떤 제안에 잘 접착된다? 고맙습니다!

+0

는 문자열을 사용 .contents''또는''대신 .text'의 .strings' 후 접합하려고/questions/16121001/suggestions-on-get-text-in-beautifulsoup) – bunji

답변

0

동일한 부모 (구문 분석 트리에서 동일한 수준)를 가진 이전 노드를 가져 오는 previous_sibling을 사용할 수 있습니다.

또한 findAll 대신 단일 요소를 검색 할 때 find을 사용하십시오.

item_span = soup.find("h1", {"class" : "product-name elim-suites"}).find("span") 

product_name = item_span.previous_sibling 
brand_name = item_span.text 

print product_name 
print brand_name 

출력 : 당신은 텍스트를 분리하거나 h1. h1.find(text=True, recursive=False)를 사용하여 텍스트를 끌어와 직접 범위에서 텍스트를 끌어 get_text를 사용하고 문자를 전달할 수

Chantecaille 
Limited Edition Protect the Lion Eye Palette 
0

:

In [1]: h ="""<h1 class="product-name elim-suites">Chantecaille<span itemprop="name" >Limited Edition Protect the Lion Eye Palette 
    ...: </span></h1>""" 

In [2]: from bs4 import BeautifulSoup 

In [3]: soup = BeautifulSoup(h, "html.parser") 

In [4]: h1 = soup.select_one("h1.product-name.elim-suites") 

In [5]: print(h1.get_text("\n")) 
Chantecaille 
Limited Edition Protect the Lion Eye Palette 


In [6]: prod, desc = h1.find(text=True, recursive=False), h1.span.text 

In [7]: print(prod, desc) 
(u'Chantecaille', u'Limited Edition Protect the Lion Eye Palette\n') 

또는 텍스트가 스팬 또한 find_all 사용 : 여기 (http://stackoverflow.com 있듯이

In [8]: h ="""<h1 class="product-name elim-suites">Chantecaille 
<span itemprop="name" >Limited Edition Protect the Lion Eye Palette</span>other text</h1>""" 


In [9]: from bs4 import BeautifulSoup 

In [10]: soup = BeautifulSoup(h, "html.parser") 

In [11]: h1 = soup.select_one("h1.product-name.elim-suites") 

In [12]: print(h1.get_text("\n")) 
Chantecaille 
Limited Edition Protect the Lion Eye Palette 
other text 

In [13]: prod, desc = " ".join(h1.find_all(text=True, recursive=False)), h1.span.text 

In [14]: 

In [14]: print(prod, desc) 
(u'Chantecaille other text', u'Limited Edition Protect the Lion Eye Palette') 
관련 문제