2015-01-20 3 views
0

나는 bs4에 멍청 아. 나는 약간의 튜토리얼을 읽고 몇 가지 간단한 예제를 시도했다. 테이블에서 데이터를 추출하고 올바르게 처리 할 수 ​​없습니다. 아름다운 스프 추출 테이블 데이터

은 html_source입니다 :

<table class="tborder" cellpadding="5" cellspacing="0" border="0" width="100%" align="center" style="margin:5px 0px 5px 0px" id="post45894054"> 
<tr> 
<td> 
<div class="alt2" style="margin:5px 0px 5px 0px; padding:5px; border:2px groove"> 
<div class="smallfont"><em> 
<br /> 
Good news today. 
</em></div> 
</div> 
</td> 
</tr> 
</table> 

는 내가 그 코드를 시도한 '좋은 소식 오늘

을 추출하고 싶습니다,하지만 난이 예상대로 작동하지 않았다 :

from bs4 import BeautifulSoup 
import urllib2 
import re 

base_url = "some url" 
html_page = urllib2.urlopen(base_url) 

soup = BeautifulSoup(html_page) 
print soup 
tables = soup.select("table .alt2 .smallfont br") 

print tables 

답변

1
from bs4 import BeautifulSoup 
soup = BeautifulSoup("""<table class="tborder" cellpadding="5" cellspacing="0" border="0" width="100%" align="center" style="margin:5px 0px 5px 0px" id="post45894054"> 
<tr> 
<td> 
<div class="alt2" style="margin:5px 0px 5px 0px; padding:5px; border:2px groove"> 
<div class="smallfont"><em> 
<br /> 
Good news today. 
</em></div> 
</div> 
</td> 
</tr> 
</table> """) 

print(soup.find("table",attrs={"class":"tborder"}).text.strip()) 
Good news today. 

print(soup.find(attrs={"class":"smallfont"}).text.strip()) 
Good news today. 
+0

그 일을 했어! –

+0

@omri_saadon, 아무런 문제가 없습니다. 몇 가지 다른 방법이 많이 있습니다. –

+0

어떻게 findall로 바꿀 수 있습니까? 왜냐하면 내가 findall로 바꿀 때 예외가 생기니까 ""NoneType '객체는 호출 가능하지 않다 "@Padraic Cunningham –

관련 문제