Python + BeautifulSoup:从网页抓取特定的表格

时间:2016-01-07 20:10:20

标签: python web-scraping beautifulsoup

我试图刮掉一张特定的桌子: this webpage

我想要抓的是股票信息。日期,公司名称,比例以及是否可以选择。

这是我到目前为止所拥有的:

from bs4 import BeautifulSoup
import urllib2

url = "http://biz.yahoo.com/c/s.html"
page = urllib2.urlopen(url) 
soup = BeautifulSoup(page.read())

alltables = soup.find_all('table')

此代码为我提供了页面上的所有表格(不止一个)。

1)我不确定如何识别我需要的表格。

2)我不确定如何将该表中的信息提取到数组或列表或我可以用于进一步分析的其他数据结构。

1 个答案:

答案 0 :(得分:4)

标记不容易抓取 - 没有id或特定class属性可用于区分表彼此。在这种情况下,我要做的是找到Payable标题单元格并找到第一个table parent

header = soup.find("b", text="Payable")
table = header.find_parent("table")

然后,您可以使用分隔符迭代跳过第一个2 - 标题和行的表行:

for row in table.find_all("tr")[2:]:
    print([cell.get_text(strip=True) for cell in row.find_all("td")])

并且,您可以将其转换为列表列表:

[[cell.get_text(strip=True) 
  for cell in row.find_all("td")]
 for row in table.find_all("tr")[2:]]
相关问题