2017-05-11 1 views
1

제거 :파이썬 : HTML 코드를 구문 분석하는 동안 줄을 건너 뛰고 나는 <code>html</code> 다음 코드 한 공백

html_doc = """ 
<h2> API guidance for developers</h2> 
<h2>Images</h2> 
<h2>Score descriptors</h2> 
<h2>Downloadable XML data files (updated daily)</h2> 
<h2> 
            East Counties</h2> 
<h2> 
            East Midlands</h2> 
<h2> 
            London</h2> 
<h2> 
            North East</h2> 
<h2> 
            North West</h2> 
<h2> 
            South East</h2> 
<h2> 
            South West</h2> 
<h2> 
            West Midlands</h2> 
<h2> 
            Yorkshire and Humberside</h2> 
<h2> 
            Northern Ireland</h2> 
<h2> 
            Scotland</h2> 
<h2> 
            Wales</h2> 
""" 

내가 처음 네 줄을 건너 뛰고 등과 East Counties 등의 텍스트 문자열에 액세스 할 수있는 방법 ?

처음 네 줄을 건너 뛰고 (내가 제거 할) 코드에 포함 많은 공백을 포함한 문자열 반환하지 않습니다 내 시도 :

from bs4 import BeautifulSoup 
soup = BeautifulSoup(html_doc, 'html.parser') 
for h2 in soup.find_all('h2'): 
    next 
    next 
    next 
    next 
    print (str(h2.children.next())) 

원하는 결과 :

East Counties 
East Midlands 
London 
North East 
... 

내가 뭘 잘못하고 있니?

+1

왜 당신은 그냥 사용할 수없는 사용 무시 'soup.find_all ('h2') [4 :]'? – Sraw

답변

4

당신은 find_all가리스트 형식을 반환 당신이 그것의 인덱스와 주변 재생할 수 있도록 [4:]처럼, 여기 slicing를 사용할 수 있으며 공백이 strip()

for h2 in soup.find_all('h2')[4:]: 
    print(h2.text.strip()) 

East Counties 
East Midlands 
London 
North East 
North West 
...  
2
from bs4 import BeautifulSoup 

soup = BeautifulSoup(html_doc, 'html.parser') 

for h2 in soup.find_all('h2')[4:]: # slicing to skip the first 4 elements 
    print(h2.text.strip()) # get the inner text of the tag and then strip the white space 
관련 문제