如何使用Beautiful Soup只选择多个表中的一个

时间:2013-12-06 15:09:22

标签: python html python-2.7 web-scraping beautifulsoup

我有一个包含4或5个不同表的html文档。我想要的那个有一个属性class =“data”。我无法弄清楚如何让BeautifulSoup返回那张桌子。

soup = BeautifulSoup(myhtml)

t = soup.findAll('table', 'class="data"')
for table in t:
    rows = table.findAll('tr')
    for tr in rows:
        cols = tr.findAll('td')
        for td in cols:
            print td

如果我删除上面的'class =“数据”',我会从每个表中得到结果。是否可以只选择class =“data”。或者,是否有其他方法来遍历表格?

2 个答案:

答案 0 :(得分:3)

class属性指定为字典,如下所示:

t = soup.findAll('table', {'class': 'data'})

如果您使用bs4,则可以使用select方法使用CSS Selector:

t = css_soup.select("table.data")

答案 1 :(得分:0)

查看以下代码:

t = soup.find_all('table', class_='data')

属性类需要under来引用