Python2.7 web抓取-列表索引超出范围

Python2.7 web抓取-列表索引超出范围,python,python-2.7,web-scraping,beautifulsoup,Python,Python 2.7,Web Scraping,Beautifulsoup,python和web抓取的新功能。我只是想勉强做些分析,但到目前为止。使用下面的代码,我只能刮取3行,并在分配年份时出现“列表索引超出范围”错误。感谢您的帮助/提示 r = requests.get('http://www.basketball-reference.com/awards/all_league.html') soup=BeautifulSoup(r.text.replace(' ','').replace('>','').encode('ascii'

python和web抓取的新功能。我只是想勉强做些分析,但到目前为止。使用下面的代码,我只能刮取3行,并在分配年份时出现“列表索引超出范围”错误。感谢您的帮助/提示

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

有些行没有
td
,因此您尝试获取空列表的元素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
2014-15
2014-15
2014-15
2013-14
2013-14
2013-14
2012-13
2012-13
etc