omri_saadon
omri_saadon

Reputation: 10631

beautiful soup extracting table data

i'm noob to bs4. i read some tutorials and tried some simple examples. i want to extract data from tables and i can't do it properly.

this is the 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> 

i would like to extract the 'Good news today'

i tried that code, but it didn't worked as i expected:

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

Upvotes: 0

Views: 1680

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

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.

Upvotes: 1

Related Questions