【发布时间】:2021-06-28 17:09:13
【问题描述】:
我有一个篮球运动员列表,我想通过我已经设置的网络抓取循环传递这些球员。球员名单是2011年NBA选秀名单。我想遍历每个球员并从他们大学最后一年获得他们的大学统计数据。问题是一些被选中的球员没有上过大学,因此没有以他们的名字格式化的网址,所以每次我通过甚至一个没有在大学打球的球员时,整个代码都会出错。我试过包括“通过”和“继续”,但似乎没有任何效果。这是迄今为止我得到的最接近的:
from bs4 import BeautifulSoup
import requests
import pandas as pd
headers = {'User Agent':'Mozilla/5.0'}
players = [
'kyrie-irving','derrick-williams','enes-kanter',
'tristan-thompson','jonas-valanciunas','jan-vesely',
'bismack-biyombo','brandon-knight','kemba-walker,
'jimmer-fredette','klay-thompson'
]
#the full list of players goes on for a total of 60 players, this is just the first handful
player_stats = []
for player in players:
url = (f'https://www.sports-reference.com/cbb/players/{player}-1.html')
res = requests.get(url)
#if player in url:
#continue
#else:
#print("This player has no college stats")
#Including this if else statement makes the error say header is not defined. When not included, the error says NoneType object is not iterable
soup = BeautifulSoup(res.content, 'lxml')
header = [th.getText() for th in soup.findAll('tr', limit = 2)[0].findAll('th')]
rows = soup.findAll('tr')
player_stats.append([td.getText() for td in soup.find('tr', id ='players_per_game.2011')])
player_stats
graph = pd.DataFrame(player_stats, columns = header)
【问题讨论】:
标签: python web screen-scraping