如何使用BeautifulSoup从特定表中获取所有行?

问题描述:

我正在学习Python和BeautifulSoup从网上抓取数据,并读取一个HTML表格。我可以将它读入Open Office,它说它是表#11。如何使用BeautifulSoup从特定表中获取所有行?

它似乎是BeautifulSoup是首选,但任何人都可以告诉我如何抓住一个特定的表和所有的行?我已经看过模块文档,但无法摆脱困境。我在网上找到的许多例子似乎比我需要的要多。

如果你有一块HTML用BeautifulSoup解析,这应该是非常简单的。总体思路是使用findChildren方法导航到您的表格,然后使用string属性获取单元格内的文本值。

>>> from BeautifulSoup import BeautifulSoup 
>>> 
>>> html = """ 
... <html> 
... <body> 
...  <table> 
...   <th><td>column 1</td><td>column 2</td></th> 
...   <tr><td>value 1</td><td>value 2</td></tr> 
...  </table> 
... </body> 
... </html> 
... """ 
>>> 
>>> soup = BeautifulSoup(html) 
>>> tables = soup.findChildren('table') 
>>> 
>>> # This will get the first (and only) table. Your page may have more. 
>>> my_table = tables[0] 
>>> 
>>> # You can find children with multiple tags by passing a list of strings 
>>> rows = my_table.findChildren(['th', 'tr']) 
>>> 
>>> for row in rows: 
...  cells = row.findChildren('td') 
...  for cell in cells: 
...   value = cell.string 
...   print "The value in this cell is %s" % value 
... 
The value in this cell is column 1 
The value in this cell is column 2 
The value in this cell is value 1 
The value in this cell is value 2 
>>> 
+0

这就是诀窍!代码工作,我应该能够根据需要进行修改。非常感谢。最后一个问题。除了在孩子th和tr的表格中搜索时,我可以遵循这些代码。这是简单地搜索我的表并返回表头和表行吗?如果我只想要表格行,我可以只搜索tr? 非常感谢! – Btibert3 2010-01-06 02:19:18

+2

是的,'.findChildren(['th','tr'])'正在搜索标签类型为“th”或“tr”的元素。如果您只想查找'tr'元素,您可以使用'.findChildren('tr')'(注意不是列表,只是字符串) – 2010-01-08 22:15:51

+0

值得注意的是[PyQuery](https://pythonhosted.org /pyquery/api.html)是BeautifulSoup的一个非常好的选择。 – 2014-06-27 15:31:14