登录
首页 >  文章 >  python教程

Player_URL字段出现NaN的解决方法

时间:2026-03-10 17:19:29 475浏览 收藏

本文深入剖析了在用BeautifulSoup爬取EliteProspects球员数据时`Player_URL`列批量返回NaN的典型顽疾,直击HTML结构误判、属性访问错位(如误从``取`href`而非其内部`EliteProspects NHL 2023–2024 统计页 提取球员个人主页链接为例,初学者常陷入三个典型误区:错误定位目标元素、混淆父/子标签属性、忽略数据标准化前置条件

? 根本原因分析

原始代码中以下三处关键问题直接导致 Player_URL 全为 NaN:

  1. 误读 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 属性属于 标签,而非其父

  2. 未声明变量 name 导致运行时错误
    df.Player == name 中的 name 未定义,触发 KeyError 或隐式布尔索引失败,pandas 回退填充 NaN。

  3. 数据清洗顺序错误
    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.eliteprospects.com/league/nhl/stats/2023-2024'
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())

⚠️ 注意事项与最佳实践

? 总结

NaN 是爬虫调试中最常见的“沉默错误”,它往往掩盖了 DOM 结构理解偏差或数据流时序错误。本文案例表明:精准定位目标节点、严格遵循父子属性归属、合理安排数据清洗阶段,是规避 NaN 的三大支柱。当遇到类似问题时,优先用 print(span.prettify()) 检查实际 HTML,再比对代码逻辑——这比盲目修改选择器更高效可靠。

以上就是《Player_URL字段出现NaN的解决方法》的详细内容,更多关于的资料请关注golang学习网公众号!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>