美丽的汤提取表数据

时间:2015-01-20 16:16:29

标签: python beautifulsoup

我是bob4的菜鸟。我阅读了一些教程并尝试了一些简单的例子。 我想从表中提取数据,我无法正确地完成。

这是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> 

我想提取今天的好消息&#39;

我试过那段代码,但它并没有像我预期的那样工作:

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 个答案:

答案 0 :(得分: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.