
本文详解为何在使用 BeautifulSoup 解析 EliteProspects 球员统计表格时 Player_URL 列持续返回 NaN,并提供可直接运行的修复方案,涵盖 HTML 结构误判、属性访问错误、数据清洗时机等关键陷阱。
本文详解为何在使用 beautifulsoup 解析 eliteprospects 球员统计表格时 `player_url` 列持续返回 nan,并提供可直接运行的修复方案,涵盖 html 结构误判、属性访问错误、数据清洗时机等关键陷阱。
在网页爬虫实践中,NaN(Not a Number)值的出现往往并非数据本身缺失,而是解析逻辑与页面实际 DOM 结构不匹配所致。以从 EliteProspects NHL 2023–2024 统计页 提取球员个人主页链接为例,初学者常陷入三个典型误区:错误定位目标元素、混淆父/子标签属性、忽略数据标准化前置条件。
? 根本原因分析
原始代码中以下三处关键问题直接导致 Player_URL 全为 NaN:
-
误读 HTML 层级结构
代码试图从 标签直接获取 href 属性:link = span.get("href") # ❌ 错误:span 本身无 href实际 HTML 结构为:
<span class="txt-blue"> <a href="/player/77237/nikita-kucherov">Nikita Kucherov (RW)</a> </span>
href 属性属于 标签,而非其父 。
未声明变量 name 导致运行时错误
df.Player == name 中的 name 未定义,触发 KeyError 或隐式布尔索引失败,pandas 回退填充 NaN。数据清洗顺序错误
df.replace() 和 applymap() 在 URL 注入前执行,但此时 Player 列仍含换行符与空格(如 "Nikita Kucherov (RW)\n"),导致后续 df.Player == name 字符串匹配失败(name 已被 .text 清洗为 "Nikita Kucherov (RW)")。
✅ 正确实现方案
以下是修复后的完整流程(已适配当前页面结构):
import requests
from bs4 import BeautifulSoup
import pandas as pd
start_url = 'https://www.php.cn/link/8641afa4db7421c9eeaf01260d8afefe'
r = requests.get(start_url)
r.raise_for_status() # 显式检查 HTTP 错误
soup = BeautifulSoup(r.content, "html.parser")
table = soup.find("table", class_="table table-striped table-sortable player-stats highlight-stats season")
# 1. 构建初始 DataFrame(保留原始未清洗数据)
headers = [th.get_text(strip=True) for th in table.find_all("th")]
df = pd.DataFrame(columns=headers)
rows = table.find_all("tr")[1:] # 跳过表头行
for row in rows:
cells = row.find_all(["td", "th"])
data = [cell.get_text(strip=True) for cell in cells]
if len(data) == len(headers):
df.loc[len(df)] = data
# 2. 【关键】先添加 Player_URL 列,再清洗数据
df["Player_URL"] = None # 初始化为空
# 3. 遍历 span.txt-blue → 定位内部 <a> → 提取 href 和 text
for span in table.find_all("span", class_="txt-blue"):
a_tag = span.find("a")
if a_tag and a_tag.has_attr("href"):
full_url = "https://www.eliteprospects.com" + a_tag["href"] # 补全相对路径
player_name = a_tag.get_text(strip=True)
# 使用 .loc 进行精确赋值(注意:需确保 player_name 在 Player 列中完全一致)
mask = df["Player"] == player_name
if mask.any():
df.loc[mask, "Player_URL"] = full_url
# 4. 【最后】统一清洗所有文本列(避免影响匹配)
text_columns = df.select_dtypes(include=["object"]).columns
df[text_columns] = df[text_columns].apply(lambda x: x.str.strip() if x.dtype == "object" else x)
# 查看结果
print(df[["Player", "Team", "GP", "Player_URL"]].head())⚠️ 注意事项与最佳实践
- 路径补全: 返回的是相对路径(如 /player/77237/...),需手动拼接为绝对 URL。
- 容错处理:添加 if a_tag and a_tag.has_attr("href") 防止空链接崩溃。
-
匹配鲁棒性:若球员名存在格式差异(如括号位置、空格数),建议对 Player 列和 player_name 同步标准化(例如移除所有括号及括号内内容):
import re df["Player_Clean"] = df["Player"].str.replace(r'\s*\(.*?\)', '', regex=True).str.strip() # 同步清洗 player_name...
- 反爬提示:该站点无强反爬,但建议添加 headers={'User-Agent': 'Mozilla/5.0...'} 并控制请求频率。
? 总结
NaN 是爬虫调试中最常见的“沉默错误”,它往往掩盖了 DOM 结构理解偏差或数据流时序错误。本文案例表明:精准定位目标节点、严格遵循父子属性归属、合理安排数据清洗阶段,是规避 NaN 的三大支柱。当遇到类似问题时,优先用 print(span.prettify()) 检查实际 HTML,再比对代码逻辑——这比盲目修改选择器更高效可靠。










