You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Transfermarkt非HTML数据表提取数据遇“NAs introduced by coercion”错误求助

解决Transfermarkt身价数据提取的NA转换错误问题

问题根源

  1. 反爬拦截:原代码直接用readLines请求页面,未处理Transfermarkt的反爬机制,导致获取的页面内容不完整或无效,后续正则截取的数据自然出错。
  2. 脆弱的正则切割:手动用正则拆分JSON结构的方式容错性极低,页面结构稍有调整就会截取到错误内容,转换数值类型时触发"NAs introduced by coercion"错误。

修复后的代码

首先安装所需依赖包(若未安装):

install.packages(c("httr", "rvest", "stringr", "jsonlite"))

运行以下代码提取数据:

library(httr)
library(rvest)
library(stringr)
library(jsonlite)

# 目标URL与请求头(模拟浏览器访问)
url <- "https://www.transfermarkt.com/manuel-neuer/marktwertverlauf/spieler/17259"
headers <- add_headers(
  "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
)

# 获取完整页面内容
response <- GET(url, headers)
page_content <- content(response, "text", encoding = "UTF-8")

# 定位包含身价数据的脚本标签
script_text <- page_content %>%
  html_elements("script") %>%
  html_text() %>%
  str_subset("'data':\\[") %>%
  first()

# 提取并标准化JSON数据片段
json_str <- str_extract(script_text, "'data':\\[.*?\\]") %>%
  str_replace("'data':", "") %>%
  str_replace_all("'", "\"")  # 转换为标准JSON格式

# 解析JSON并整理成数据框
raw_data <- fromJSON(json_str)
res <- data.frame(
  Date = as.Date(raw_data$datum_mw, format = "%b %d, %Y"),
  MarketValue = as.numeric(raw_data$y),
  Club = raw_data$verein,
  Age = as.numeric(raw_data$age)
)

# 查看结果
head(res)

关键改进点

  • 反爬绕过:通过设置User-Agent模拟浏览器请求,确保获取完整的目标页面内容。
  • 结构化数据解析:利用JSON解析工具替代手动正则切割,大幅提升数据提取的稳定性,避免因页面小改动导致的错误。
  • 精准类型转换:直接从解析后的JSON对象中提取字段,转换类型时不会出现无效值,彻底解决NA转换错误。

内容的提问来源于stack exchange,提问作者TomTe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 04:07:09