使用rvest提交表单报错:form无action属性,如何自动化下载数据?
解决方案
你的问题核心是页面表单缺少action属性,导致html_form_submit()无法确定提交目标。你猜测的提交地址https://www.offenerhaushalt.at/downloads/ghdByParams是正确的,以下两种方法可以解决文件下载问题:
方法1:手动补全表单action后用rvest提交
直接修改解析到的表单对象,补上action属性再提交:
library(rvest) library(httr) # 读取页面并获取表单 download_page <- read_html("https://www.offenerhaushalt.at/gemeinde/innsbruck/download") target_form <- html_form(download_page)[[1]] # 手动设置表单的提交地址 target_form$action <- "https://www.offenerhaushalt.at/downloads/ghdByParams" # 填充表单参数 filled_form <- html_form_set(target_form, year = "2022", haushalt = "fhh", rechnungsabschluss = "va", origin = "gemeinde") # 提交表单并获取响应 response <- html_form_submit(filled_form) # 保存文件(可自定义文件名) writeBin(content(response, "raw"), "innsbruck_haushalt_2022.xlsx")
方法2:直接用httr发送POST请求(更简洁)
绕过表单解析,直接构造POST请求到目标地址,适合逻辑简单的表单:
library(httr) # 定义请求地址和参数 submit_url <- "https://www.offenerhaushalt.at/downloads/ghdByParams" request_params <- list( year = "2022", haushalt = "fhh", rechnungsabschluss = "va", origin = "gemeinde" ) # 发送POST请求,自动编码表单参数 response <- POST(submit_url, body = request_params, encode = "form") # 检查请求是否成功(失败则抛出错误) stop_for_status(response) # 从响应头提取原始文件名(如果服务器返回) filename <- sub('attachment; filename="?([^"]+)"?', '\\1', headers(response)$`content-disposition`) # 若提取失败则使用自定义文件名 if (is.na(filename)) filename <- "innsbruck_haushalt_2022.xlsx" # 保存二进制文件 writeBin(content(response, "raw"), filename)
说明
- 两种方法都需要处理二进制响应内容,用
writeBin()保存可以避免文件损坏(因为下载的是Excel/CSV这类二进制格式)。 - 第二种方法无需依赖rvest解析表单,更高效,也避免了表单属性缺失的问题。
内容的提问来源于stack exchange,提问作者Moritz Schwarz
相关产品推荐
相关产品推荐

