2016-04-07 19 views
0

python和网页抓取的新手段。我试图抓取http://www.basketball-reference.com/awards/all_league.html进行一些分析,只得到了目前为止。使用下面的代码,我可以在指定年份的时候只擦除3行并获取“列表索引超出范围”的错误。任何帮助/提示表示赞赏。Python 2.7网页抓取 - 列表索引超出范围

r = requests.get('http://www.basketball-reference.com/awards/all_league.html') 
soup=BeautifulSoup(r.text.replace(' ','').replace('>','').encode('ascii','ignore'),"html.parser") 
all_league_data = pd.DataFrame(columns = ['year','team','player']) 


stw_list = soup.findAll('div', attrs={'class': 'stw'}) # Find all 'stw's' 
for stw in stw_list: 
    table = stw.find('table', attrs = {'class':'no_highlight stats_table'}) 
    for row in table.findAll('tr'): 
     col = row.findAll('td') 
     year = col[0].find(text=True) 
     print year 

回答

0

某些行没有td,因此您尝试获取空列表的元素0。

做:

r = requests.get('http://www.basketball-reference.com/awards/all_league.html') 
soup=BeautifulSoup(r.text.replace(' ','').replace('>','').encode('ascii','ignore'),"html.parser") 
all_league_data = pd.DataFrame(columns = ['year','team','player']) 

stw_list = soup.findAll('div', attrs={'class': 'stw'}) # Find all 'stw's' 
for stw in stw_list: 
    table = stw.find('table', attrs = {'class':'no_highlight stats_table'}) 
    for row in table.findAll('tr'): 
     col = row.findAll('td') 
     if col: 
      year = col[0].find(text=True) 
      print year 
0

这是因为灰线是一个tr和是空的。 做一个检查,如果山坳

col = row.findAll('td') 
    if col: 
     year = col[0].find(text=True) 
     print year 

,并给出正确的结果

2014-15 
2014-15 
2014-15 
2013-14 
2013-14 
2013-14 
2012-13 
2012-13 
etc