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

如何使用R通过含onclick属性的按钮下载PDF文件

问题描述

需要从荷兰政府PUC网站下载特定PDF文件,该文件需点击页面上的“Maak een pdf”按钮生成,但按钮的href属性是一段JavaScript代码:

javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$cphContent$Main$ctl00$DocumentHeader$ctl00", "", true, "", "", false, true))

尝试用rvest定位该属性后,直接使用download.file函数下载失败,报错提示无法打开目标文件,具体代码及报错如下:

library(tidyverse)
library(rvest)

link = "https://puc.overheid.nl/natuurvergunningen/doc/PUC_746615_17/1/"

button <- link %>%
  read_html() %>%
  html_nodes(".download-als") %>%
  html_nodes("a") %>%
  html_attr("href") 
button
#> [1] "javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(\"ctl00$cphContent$Main$ctl00$DocumentHeader$ctl00\", \"\", true, \"\", \"\", false, true))"

download.file(button, destfile = "Downloads/test.pdf")
#> Warning in download.file(button, destfile = "Downloads/test.pdf"): URL
#> javascript:WebForm_DoPostBackWithOptions(new
#> WebForm_PostBackOptions("ctl00$cphContent$Main$ctl00$DocumentHeader$ctl00", "",
#> true, "", "", false, true)): cannot open destfile 'Downloads/test.pdf', reason
#> 'No such file or directory'
#> Warning in download.file(button, destfile = "Downloads/test.pdf"): download had
#> nonzero exit status
解决方案

由于该按钮的下载逻辑依赖JavaScript触发服务器端PostBack操作,无法通过静态解析直接获取PDF链接,必须模拟真实浏览器交互行为,使用RSelenium包可实现需求,具体步骤如下:

1. 准备工作

  • 安装RSelenium包:install.packages("RSelenium")
  • 确保本地已安装对应浏览器驱动(如ChromeDriver),或使用RSelenium::rsDriver()自动下载配置。

2. 完整代码实现

library(RSelenium)

# 定义下载路径(需确保路径存在,不存在则自动创建)
download_path <- normalizePath("./Downloads")
dir.create(download_path, showWarnings = FALSE)

# 配置Chrome浏览器偏好:自动下载PDF,不弹窗
chrome_options <- list(
  chromeOptions = list(
    prefs = list(
      "download.default_directory" = download_path,
      "download.prompt_for_download" = FALSE,
      "download.directory_upgrade" = TRUE,
      "plugins.always_open_pdf_externally" = TRUE
    )
  )
)

# 启动Chrome浏览器会话
driver <- rsDriver(browser = "chrome", extraCapabilities = chrome_options)
remote_driver <- driver[["client"]]

# 打开目标页面
remote_driver$navigate("https://puc.overheid.nl/natuurvergunningen/doc/PUC_746615_17/1/")

# 定位“Maak een pdf”按钮并模拟点击
pdf_button <- remote_driver$findElement(using = "css selector", value = ".download-als a")
pdf_button$clickElement()

# 等待下载完成(根据文件大小调整等待时长)
Sys.sleep(5)

# 关闭浏览器会话
remote_driver$close()
driver[["server"]]$stop()

代码说明

  • 浏览器偏好配置:通过Chrome的prefs参数指定PDF自动下载路径,避免弹出下载确认窗口。
  • 元素定位:使用CSS选择器.download-als a精准定位触发按钮,模拟用户点击操作。
  • 等待时间:Sys.sleep(5)用于等待服务器生成并返回PDF文件,需根据文件大小适当调整时长。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 16:27:01