如何用R语言rvest提取世界银行CPI通胀率网页的悬停时间序列数据?
用R提取世界银行消费者价格通胀率数据
方案1:使用rvest直接抓取页面数据
如果目标是页面中的国家数据表格或顶部折线图的时间序列数据,可按以下步骤操作:
- 加载依赖包
library(rvest) library(dplyr) library(stringr) library(jsonlite)
- 读取目标页面
html_url <- read_html("https://data.worldbank.org/indicator/FP.CPI.TOTL.ZG")
- 提取国家通胀率表格数据
页面中包含各国历年通胀数据的表格,可通过CSS选择器定位并提取:
# 定位表格并转为数据框 inflation_table <- html_url %>% html_element("table#indicator-data") %>% html_table(header = TRUE, fill = TRUE) # 清理数据:过滤无效行、转换数值格式 inflation_clean <- inflation_table %>% filter(!is.na(`Country Name`) & `Country Name` != "World") %>% mutate(across(starts_with("2"), ~ str_remove_all(., "\\[.*\\]") %>% as.numeric))
- 提取顶部折线图的全球时间序列数据
折线图的数据以JSON形式内嵌在页面脚本中,可通过字符串匹配提取并解析:
# 提取包含图表数据的脚本内容 chart_script <- html_url %>% html_element(xpath = "//script[contains(text(), 'chartData')]") %>% html_text() # 提取chartData对应的JSON片段并解析 chart_data_json <- str_extract(chart_script, 'chartData\\s*=\\s*(\\{.*?\\});') %>% str_remove('chartData\\s*=\\s*') %>% str_remove(';') chart_data <- fromJSON(chart_data_json)$series[[1]]$data %>% as.data.frame() %>% rename(Year = V1, Inflation_Rate = V2) %>% mutate(Year = as.integer(Year))
方案2:使用世界银行官方包wbstats(更稳定)
如果不想处理页面结构变化的问题,推荐使用官方API包,无需网页抓取:
library(wbstats) # 获取全球历年通胀率数据 global_inflation <- wb_data( indicator = "FP.CPI.TOTL.ZG", country = "WLD", start_date = 1960, end_date = 2024 )
内容的提问来源于stack exchange,提问作者newfinder
相关产品推荐
相关产品推荐

