请求更新雅虎基金元数据爬取R代码:节点选择器失效
修复Yahoo Finance基金元数据爬取的R代码
原代码失效是因为Yahoo Finance页面结构更新,旧的CSS选择器已无法定位目标数据。以下是调整后的代码,适配当前页面结构:
library(rvest) library(purrr) library(dplyr) ticker <- "IVV" url <- paste0("https://finance.yahoo.com/quote/", ticker) ivv_html <- read_html(url) # 定位包含统计数据的表格行,当前页面中统计项以表格行形式存在 df <- ivv_html %>% html_nodes('table[data-test="summary-table"] tr') %>% # 目标统计数据所在表格 map_dfr(~{ label <- html_nodes(.x, 'td:nth-child(1)') %>% html_text(trim = TRUE) value <- html_nodes(.x, 'td:nth-child(2)') %>% html_text(trim = TRUE) tibble(label, value) }) # 筛选需要的指标 df %>% filter(label %in% c("NAV", "PE Ratio (TTM)", "Yield", "Beta (5Y Monthly)", "Expense Ratio (net)"))
说明
- 改用
table[data-test="summary-table"]定位统计数据表格,这个属性是页面中用于标识统计表格的测试属性,稳定性比随机生成的class更高 - 每个统计项是表格的一行(
tr),通过td:nth-child(1)提取标签,td:nth-child(2)提取对应值
内容的提问来源于stack exchange,提问作者Brad Horn
相关产品推荐
相关产品推荐

