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

使用rvest提交表单报错:`Form`不含`action`属性的解决咨询

解决rvest提交saferproducts.gov表单时的action属性缺失错误

问题原因

你遇到的form doesn't contain a action attribute错误,是因为该网站的表单action属性并非静态写入HTML,而是通过JavaScript动态注入到DOM中的。rvest只能抓取初始加载的静态HTML,因此无法识别到这个属性,导致提交失败。

解决方案1:手动补充表单的action属性

直接给解析后的表单对象添加缺失的action属性,再进行提交:

library(rvest)

# 初始化会话
url <- 'https://www.saferproducts.gov/PublicSearch'
session <- html_session(url)

# 提取页面表单
form_unfilled <- session %>% html_node("form") %>% html_form()

# 手动添加表单提交的目标地址(从浏览器网络请求分析获取)
form_unfilled$action <- "/PublicSearch/Results"

# 填充搜索关键词参数
form_filled <- form_unfilled %>%
  set_values("searchParameter.AdvancedKeyword" = "amazon")

# 提交表单(指定提交按钮名称避免歧义)
result_session <- submit_form(session, form_filled, submit = "searchButton")

# 示例:提取搜索结果标题
result_titles <- result_session %>% html_nodes(".result-title a") %>% html_text()
print(result_titles)

解决方案2:直接构造POST请求绕过表单解析

如果表单结构复杂,也可以跳过rvest的表单解析步骤,直接构造符合要求的POST请求:

library(httr)
library(rvest)

# 初始化会话以获取CSRF验证令牌
session <- html_session("https://www.saferproducts.gov/PublicSearch")
csrf_token <- session %>% html_node("input[name='__RequestVerificationToken']") %>% html_attr("value")

# 构造POST请求参数(参数可从浏览器网络请求中抓取)
post_params <- list(
  "__RequestVerificationToken" = csrf_token,
  "searchParameter.AdvancedKeyword" = "amazon",
  "searchParameter.SearchType" = "Advanced",
  "searchParameter.PageNumber" = "1",
  "searchParameter.PageSize" = "10"
)

# 发送POST请求
response <- POST(
  url = "https://www.saferproducts.gov/PublicSearch/Results",
  body = post_params,
  encode = "form",
  cookies = session$cookies
)

# 解析并提取结果
result_page <- content(response)
result_titles <- result_page %>% html_nodes(".result-title a") %>% html_text()
print(result_titles)

关键说明

  • 表单的action地址和参数可以通过浏览器开发者工具的网络面板,抓取实际搜索请求获取;
  • __RequestVerificationToken是网站的CSRF防护参数,必须从初始页面的隐藏输入框中提取,否则请求会被拒绝;
  • 如果后续遇到动态加载的内容,可能需要结合RSelenium或playwright等工具处理JavaScript渲染的页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:30:59