如何用BeautifulSoup爬取CBS体育全位置NFL球员搜索结果数据?
实现NFL全位置球员数据爬取的最优方案
核心思路:不需要手动枚举所有位置参数,先动态抓取页面下拉框内的所有位置编码,再循环遍历每个位置发起请求爬取数据,既避免参数写错漏写,后续网站调整位置选项也能自动适配。
首先注意原代码存在变量名错误:你定义的表格变量是player_table,循环时用了未定义的all_player_table,需要先修正这个问题。
具体实现步骤
- 第一步:首次请求页面时,先解析位置下拉选框,提取所有有效位置的参数值
- 第二步:将单位置爬取逻辑封装为可复用函数,传入位置参数即可爬取对应数据
- 第三步:遍历所有位置参数调用爬取函数,添加请求间隔避免触发网站反爬
完整可运行代码
from bs4 import BeautifulSoup import requests import time # 封装单位置爬取函数 def crawl_players_by_position(pos_code): base_url = f"https://www.cbssports.com/nfl/playersearch?POSITION={pos_code}&print_rows=9999" # 添加UA头模拟浏览器请求,降低被反爬概率 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" } try: resp = requests.get(base_url, headers=headers, timeout=10) resp.raise_for_status() soup = BeautifulSoup(resp.text, 'html.parser') player_table = soup.find('table', class_='data') if not player_table: print(f"位置{pos_code}无有效数据") return # 遍历球员行 for tr in player_table.find_all('tr', class_=['row1','row2']): tds = tr.find_all('td') if len(tds) >=3: print(f"Player:{tds[0].text.strip()} , Position:{tds[1].text.strip()} , Team: {tds[2].text.strip()}") except Exception as e: print(f"爬取位置{pos_code}出错:{str(e)}") if __name__ == "__main__": # 先请求默认页面,提取所有位置参数 init_url = "https://www.cbssports.com/nfl/playersearch?POSITION=RB&print_rows=9999" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" } init_resp = requests.get(init_url, headers=headers) init_soup = BeautifulSoup(init_resp.text, 'html.parser') position_select = init_soup.find('select', {'name': 'POSITION'}) # 提取所有有效位置参数,过滤空值 position_list = [] for option in position_select.find_all('option'): pos_val = option.get('value', '').strip() if pos_val: position_list.append(pos_val) print(f"共获取到{len(position_list)}个位置,开始爬取...") # 遍历爬取所有位置 for pos in position_list: print(f"\n========== 正在爬取位置:{pos} ==========") crawl_players_by_position(pos) # 每次请求间隔1.5秒,避免触发反爬 time.sleep(1.5)
优化建议
- 若需要持久化存储数据,可将打印逻辑替换为写入CSV文件、Excel或数据库的操作
- 可添加断点续爬逻辑,意外中断后不需要从头开始爬取
- 若需要更完善的字段,可根据页面结构扩展提取球员ID、详情页链接等信息
内容的提问来源于stack exchange,提问作者Meruemu
相关产品推荐
相关产品推荐

