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

使用R爬取瑞士税务网站汇率表遇{xml_nodeset (0)}及API失效求助

无需V8的R语言爬取瑞士税务汇率表方案

方案1:用RSelenium模拟浏览器渲染(最可靠)

页面为动态渲染结构,read_html仅能获取初始静态HTML,RSelenium可模拟真实浏览器加载完整页面,拿到渲染后的内容。

  1. 安装依赖包:
install.packages(c("RSelenium", "rvest"))
library(RSelenium)
library(rvest)
  1. 启动Chrome驱动(需确保本地安装Chrome及对应版本的ChromeDriver,也可替换为Firefox):
# 启动驱动,端口可自定义
driver <- rsDriver(browser = "chrome", port = 4567L)
remDr <- driver[["client"]]
  1. 访问目标页面并等待加载:
remDr$navigate("https://www.ictax.admin.ch/extern/de.html#/ratelist/2022")
# 等待5秒让页面渲染完成,可根据网络情况调整时长
Sys.sleep(5)
  1. 提取并解析汇率表:
# 获取渲染后的页面源码
page_html <- remDr$getPageSource()[[1]] %>% read_html()
# 提取汇率表转为数据框
exchange_rates <- page_html %>% 
  html_node("#exchangeRates table") %>% 
  html_table(header = TRUE)

# 查看结果
head(exchange_rates)
  1. 关闭驱动:
remDr$close()
driver$server$stop()

方案2:尝试带参数的API请求

你之前找到的接口可能需要指定年份参数,试试以下请求:

library(httr)
library(jsonlite)

# 请求2022年汇率数据
resp <- GET("https://www.ictax.admin.ch/extern/api/coreGadget/exchangeRates",
            query = list(year = 2022))

if (http_status(resp)$category == "Success") {
  rate_data <- fromJSON(content(resp, "text"))
  rate_df <- as.data.frame(rate_data)
  head(rate_df)
} else {
  message("API请求失败,可能是公司网络限制导致")
}

方案3:提取页面内嵌的静态数据

部分动态页面会把数据藏在script标签中,尝试提取这部分内容:

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

page <- read_html("https://www.ictax.admin.ch/extern/de.html#/ratelist/2022")
# 筛选包含汇率数据的script标签
script_text <- page %>% 
  html_nodes("script") %>% 
  html_text() %>% 
  str_subset("exchangeRates")

if (length(script_text) > 0) {
  # 提取JSON部分(需根据实际内容微调正则表达式)
  json_str <- str_extract(script_text, "\\{\"exchangeRates\":.*\\}")
  rate_data <- fromJSON(json_str)
  head(rate_data$exchangeRates)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:05:18