使用R从网页“单击”下载.csv文件

nbnkbykc  于 2023-03-20  发布在  其他
关注(0)|答案(1)|浏览(97)

当我使用以下参数单击此页上的下载按钮时:

  • 期货
  • 选择:CRA
  • 开始日期:2023年3月16日
  • 截止日期:2023年3月16日

我在我的下载文件夹中得到了一个csv文件。我想用R把它作为一个 Dataframe 。
我尝试的代码下载了整个HTML页面,而不仅仅是csv文件。

library(httr)

POST("https://www.m-x.ca/en/trading/data/historical?symbol=CRA&from=2023-03-16&to=2023-03-16#CRAH23-20230316",
     body = list(`frmHisto[]` = "Futures", 
                 `symbol[]` = "CRA",
                 `from[]` = "2023-03-16",
                 `to[]` = "2023-03-16"), 
     encode = "form",
     write_disk("quote_CRA_20230316.csv")) -> res
tzcvj98z

tzcvj98z1#

我不确定post,但这里有一个RSelenium的方式来下载文件:

# Load library ---------------------------------------------------------------
library(RSelenium)

# The URL changes depending on what parameters are chosen
# So we don't have to use RSelenium to set parameters!
# It can be done with the URL

# Choose values------------------------------------------------------------

transaction_type <- "Futures"
symbol <- "CRA"
start_date <- "2023-03-16"
end_date <- "2023-03-16"

url <- paste0("https://www.m-x.ca/en/trading/data/historical?symbol=",
              symbol,
              "&from=",
              start_date,
              "&to=",
              end_date)

# I think this bit just specifies where on the page we start, so probably not
# needed:     #CRAH23-20230316

# start RSelenium ------------------------------------------------------------

# set up RSelenium ------------------------------------------------------
rD <- rsDriver(browser="firefox", port=4547L, chromever = NULL)
remDr <- rD[["client"]]

# Navigate to webpage -----------------------------------------------------
remDr$navigate(url)

# Click on the download button -----------------------------------------------------
remDr$findElements("id", "btnDnld")[[1]]$clickElement()

相关问题