使用RSelenium无法直接上传文件的技术求助
问题根源
你找错了操作元素:upload_locations是网站用来唤起文件选择对话框的美化按钮,而只有<input type="file">类型的元素才能直接接收文件路径,普通按钮无法通过sendKeysToElement传递文件路径。
修正方案
- 定位页面中真实的文件上传输入元素(PRISM页面中该元素的id为
location_file) - 直接向这个元素传递文件路径,无需点击按钮
修正后的完整代码
# Set up RSelenium ------------------------------------------------------- ## load packages ---- library(RSelenium) library(rvest) library(tidyverse) library(netstat) library(here) library(dplyr) library(readr) ##Set Default download folder ---- eCaps <- list( chromeOptions = list(prefs = list( "profile.default_content_settings.popups" = 0L, "download.prompt_for_download" = FALSE, "download.default_directory" = gsub(pattern = '/', replacement = '\\\\', x = here("WebData")) # download.dir ) ) ) default_folder = here("WebData") ## Open a chrome browser session with RSelenium ---- rs_driver_object <-rsDriver( browser = 'chrome', chromever ='108.0.5359.71', port = free_port(), extraCapabilities = eCaps # 补上原代码遗漏的配置参数 ) remDr <- rs_driver_object$client ##Input Locations File LocationFile <- gsub(pattern = "/", replacement = "\\\\", x = here("InputData/prism_rr_precip_stations.csv")) #Navigate to PRISM Explorer webpage---- URL <- "https://prism.oregonstate.edu/explorer/bulk.php" remDr$navigate(URL) # 替换原有上传逻辑:定位真实文件输入元素并传递路径 file_input <- remDr$findElement(using = "id", value = "location_file") file_input$sendKeysToElement(list(LocationFile))
额外说明
- 原代码中
rsDriver调用时未传入extraCapabilities = eCaps,导致你设置的下载目录等配置未生效,修正代码已补上该参数。 - 确保
LocationFile是绝对路径,here()生成的路径符合要求,相对路径可能导致上传失败。
内容的提问来源于stack exchange,提问作者Paul NoCal
相关产品推荐
相关产品推荐

